I came across a method in my code where the rounded value is not calculated correctly in my code. I know about the problem of comparing double values caused by unexpected results.
Example
double x = 19.08;
double y = 2.01;
double result = 21.09;
if (x + y == result)
{
}
Explanation here: http://csharpindepth.com/Articles/General/FloatingPoint.aspx
However, so far I have expected the Math.Round () method to be accurate even with double values.
Take a look at this code.
var decimals = 2;
var value1 = 4.725;
var value2 = 4.725M;
var result1 = Math.Round(value1, decimals, MidpointRounding.ToEven);
var result2 = Math.Round(value1, decimals, MidpointRounding.AwayFromZero);
var result3 = Math.Round(value2, decimals, MidpointRounding.ToEven);
var result4 = Math.Round(value2, decimals, MidpointRounding.AwayFromZero);
Console.WriteLine("Double (ToEven): {0}", result1);
Console.WriteLine("Double (AwayFromZero): {0}", result2);
Console.WriteLine("Decimal (ToEven): {0}", result3);
Console.WriteLine("Decimal (AwayFromZero): {0}", result4);
It is clear to me that result2 should be 4.73. However, it is not. Can someone explain why?
source
share