NCalc precision problems

2.1k Views Asked by At

I got some rounding problems with NCalc. My problem is quite simple. just add 0.5 and 0.5555. expected result is 1.0555. This i need to round to 3 fractions. 1.056

float and double should not cause me any precision problems at a 5 digit number. However NCalc does.

Expression ex = new Expression("0.5 + 0.5555");
object result = ex.Evaluate();

result  1.0554999999999999  object {double}

This will round down instead of up. Even if the error is 0.0000000~~~~1. Anyone have any ideas how I can solve this ?

3

There are 3 best solutions below

0
On

Not the very best solution.. but a solution.

result.ToString(); 

will give me the "correct" number back. And by rounding it to 3 fractions it will yield the correct result.

0
On

NCalc adds those two numbers as System.Double values, so the result(also System.Double) is correct.

If NCalc does not allow to force this operation as on two System.Decimal values then maybe you should look for some another library.

0
On

Force NCalc to use decimals by passing parameters with m:

 Expression ex = new Expression("[a1] + [a2]");
 ex.Parameters["a1"] = 0.5m;
 ex.Parameters["a2"] = 0.555m;
 object result = ex.Evaluate();