Method Math.Round does not round correctly

3

I'm having problems with the Math.Round() method in C #, some values that it does not round properly, I'll give some examples:

Math.Round(1190.245, 2)

1190.245 it should round to 1190.25 since it ends with 5 and the 5 increases only it rounds to 1190.24

Another case

Math.Round(1190.004999999, 2)

It should round to 1190.01 but round to 1190 .

    
asked by anonymous 06.02.2018 / 20:29

1 answer

2

You have two problems with your code. The first is that the adopted pattern of rounding is the same. If you want to change you have to configure it with the MidpointRounding .

But in this case it still will not give the expected result because it is using a double type that is not accurate, so the number is a little less than 1190.245, which would still cause it to round down. If you want accuracy you should use decimal .

Here I show you that it works by configuring midpoint , as long as the value is really accurate or slightly above, but it still will not work if it is a little below what you see. And I'll show you that if you use a decimal it works at the number you want.

Do not use binary floating-point types if you want accuracy . Most of the financial software I see has this bug causing damage to its users.

The second example is with the correct and visible result. Even if you use decimal and setting up the midpoint will still give you the same result. If you want other things you need to define a criterion and decide what to do, that's normal.

using System;
using static System.Console;
using static System.Math;

public class Program {
    public static void Main() {
        WriteLine(Round(1190.205, 2, MidpointRounding.AwayFromZero));
        WriteLine(Round(1190.245M, 2, MidpointRounding.AwayFromZero));
    }
}

See running on .NET Fiddle . And no Coding Ground . Also I placed GitHub for future reference .

    
06.02.2018 / 21:00