Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c# - DataTable Compute Value is too large or too small for type Int32

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()); 

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 :

"Value is either too large or too small for Type '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.

A little hand on that ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

string expression = "330200000.0*450000.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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...