对于Int32类型,DataTable计算值太大或太小 [英] DataTable Compute Value is too large or too small for type Int32

查看:325
本文介绍了对于Int32类型,DataTable计算值太大或太小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近遇到了一种使用数据表对象的计算方法在C#中评估表达式的方法。这是一段代码:

I recently came across a way to evaluate expression in C#, using the compute method of a datatable object. Here is a piece of code :

    string expression = "330200000*450000";
    var loDataTable = new DataTable();
    var loDataColumn = new DataColumn("Eval", typeof(double), expression);
    loDataTable.Columns.Add(loDataColumn);
    loDataTable.Rows.Add(0);
    MessageBox.Show(((double)(loDataTable.Rows[0]["Eval"])).ToString()); 

如果您输入 300 * 2之类的简单表达式,则可以,但是返回的表达式较大的数字将不起作用,我收到消息:

If you put a simple expression like "300*2" this will work, however an expression returning a large number would not work, I get the message :


对于'Int32'类型,值太大或太小。 / p>

"Value is either too large or too small for Type 'Int32'."

我试图强制类型加倍,但由于某种原因,该错误仍然指向有关Int32类型的内容,我不确定该在哪里

I tried to force the type to double, but for some reason the error still points to something regarding Int32 type which I am not sure where it comes from.

对此有一点帮助?

推荐答案

在方程式中的值后面加上 .0:

Append ".0" to the values in your equation:

string expression = "330200000.0*450000.0";

如您所说,如果等式已按原样输入(即不带 .0 ),那么您可能必须进行一些令人不快的字符串操作才能实现此目的。我提出了以下内容,尽管我敢肯定它可以做得更好:

If, as you said, the equation has been entered as it is (i.e. without the ".0") by the user, then you might have to engage in some vaguely unpleasant string manipulation to achieve this. I came up with the following, although I'm certain it can be done better:

string expression = "330200000*450000"; // or whatever your user has entered
expression = Regex.Replace(
    expression, 
    @"\d+(\.\d+)?", 
    m => {
         var x = m.ToString(); 
         return x.Contains(".") ? x : string.Format("{0}.0", x);
    }
);
var loDataTable = new DataTable();
var computedValue = loDataTable.Compute(expression, string.Empty);

正则表达式试图说明您的用户是否已经在小数点后放置了小数他们方程中的任何数字。

The regular expression attempts to account for whether or not your user has already put a decimal on the end of any of the numbers within their equation.

这篇关于对于Int32类型,DataTable计算值太大或太小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆