Calculating a String in C#

476 Views Asked by At

I want to calculate a string in C# using either NCalc or DynamicExpresso library, the problem is, when the calculation gets complex and the numbers are big, it returns the wrong result. For example the code below returns -808182895 when it should return 3486784401

string value = "387420489*9";
value = new Interpreter().Eval(value).ToString();

Am i doing anything wrong? Thanks for the help.

1

There are 1 best solutions below

0
On BEST ANSWER

Try the following:

(long)387420489 * (long)9

Dynamic Expresso has a web shell here where you can test the expressions;

http://dynamic-expresso.azurewebsites.net/

While testing on this web shell, I realized that;

 387420489L * 9 => Syntax error (at index 9). => does not accept type suffix
 (long)387420489 * 9 => -808182895 => overflow
 387420489 * (long)9 => 3486784401 => OK

 2147483647 + 1 => -2147483648 => int.MaxValue + 1 = int.MinValue (overflow)
 2147483648 + 1 => 2147483649 => When does not fit into Int32, interpreted as long

While most of these can be regarded as by design (considering how Dynamic Expresso evaluates the statement), there can still be further improvement.

Think of Javascript for example.

387420489*9 => 3486784401

The question is, is what we need

  1. to execute the given arithmetic expression correctly, as we and the end-user expects,
  2. to execute the given arithmetic expression the C# way?

The former, I think.