Reputation: 859
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 ?
Upvotes: 8
Views: 2374
Reputation: 11
string expression = "-2+4.00*0.20+3.000/06";
char[] separators = new char[4] { '+', '-', '*', '/' };
string[] numbers = expression.Split(separators, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < numbers.Length; i++)
{
Regex r1 = new Regex(numbers[i]);
expression = r1.Replace(expression, "X", 1);
}
for (int i = 0; i < numbers.Length; i++)
{
decimal d = Convert.ToDecimal(numbers[i]);
numbers[i] = d.ToString("0.####");//# 0-28
if (!numbers[i].Contains(".")) numbers[i] += ".0";
}
for (int i = 0; i < numbers.Length; i++)
{
Regex r2 = new Regex("X");
expression = r2.Replace(expression, numbers[i], 1);
}
if (expression.Contains("/0.0")) return;
decimal dec = Convert.ToDecimal(new DataTable().Compute(expression, ""));
result = dec.ToString("0.####");//# 0-28
Upvotes: 0
Reputation: 51
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.
Upvotes: 5