1
Vote

Calculation of simple math exrpession gives wrong result

description

Hi,

I am using ExressionEvaluator version v4.0.30319 and when I try to calculate simple math expression like
((3/2)(3/2)10)3.14
I get a result of 31.4 instead of correct result of 70.65.

Below is the sample test code I use,

var expr2 = new CompiledExpression("((3/2)(3/2)10)
3.14");
Console.WriteLine(expr2.Eval());

Let me know if there is any work around to fix this.

Regards,
Shreekanth

comments

shreekanthks wrote Oct 12, 2016 at 5:04 PM

The version - 2.0.4.0

RupertAvery wrote Oct 15, 2016 at 1:36 PM

It's working perfectly fine. If you try that code in Visual Studio you will get the same answer.

The reason why you are getting a different value than you expected is due to implicit data types.

Since there are no decimal points or float literal suffixes, 3/2 is being evaluated as integer division. the result of that integer division is 1. So 3/2 * 3/2 * 10 is equivalent to 1 * 1 * 10 or 10. SInce you are multiplying by an implicit floating point (a number with decimal point, 3.14). The 10 is converted to float in order to be compatible with the 3.14, and you end up with 31.4.

What you probably want to do is:

((3/2f)*(3/2f)10f)3.14;

The f forces the number to floating point.

This is part of the C# spec and as much as it is useful in some cases to have javascript-like number semantics where everything is a float, it will just create problems with the underlying C# specification upon which the parser is built.

shreekanthks wrote Oct 19, 2016 at 8:20 PM

Makes sense, Thank You