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

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

问题描述

我最近遇到了一种在 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',值要么太大要么太小."

"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 类型来说太大或太小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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