Math.Round () gives an unexpected result for double

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)
    {
        // this is never reached
    }

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); // outputs 4.72
        Console.WriteLine("Double (AwayFromZero): {0}", result2); // outputs 4.72 (expected: 4.73)
        Console.WriteLine("Decimal (ToEven): {0}", result3); // outputs 4.72
        Console.WriteLine("Decimal (AwayFromZero): {0}", result4); // outputs 4.73

It is clear to me that result2 should be 4.73. However, it is not. Can someone explain why?

+5
source share
4 answers

, " ", 4.725 ( 4.625) double.

4,7249999999999996447286321199499070644378662109375

, - , , . , 4.725, , , . , , .

+10

value1 4.724999999999999999999999999999999. 4.73 4.72?

+1

. , 0,5 + 0,5, 1.0, , , - 0.99999 1.00001. .

/: http://www.learncpp.com/cpp-tutorial/25-floating-point-numbers/ , #.

0

Convert.ToDouble(1.ToString( "f2" )) Math.Round(1, 2)

0

All Articles