Math.Round method does not round correctly

Asked

Viewed 2,206 times

3

I’m having trouble with the method Math.Round() in C#, some values that it does not round correctly, I will give some examples:

Math.Round(1190.245, 2)

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

Another case

Math.Round(1190.004999999, 2)

He should round up to 1190.01 but rounds to 1190.

  • Welcome to the forum, post your code to facilitate the analysis, however, recommend taking a pass here to know how things work.

  • The code is this friend, I pass these values in this method and it returns wrong, only this, I look for an explanation

  • Take a look at this link, I think it will be enough for you to understand what is happening.

1 answer

2


There are two problems in the code. The first is that the adopted rounding pattern is the same. If you want to change you have to configure with the enumeration MidpointRounding.

But in this case it still won’t give the expected result because it’s using a type double which has no accuracy, so in number is a little less than 1190.245, which would still round down. If you want accuracy you should use a decimal.

Here I show that it works by configuring the midpoint, provided that the value is actually exact or a little higher, but it still won’t work if it’s a little below what you’re seeing. And I show that using a decimal works on 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 harm to its users.

The second example is with the correct and visible result. Even if using decimal and configure the midpoint will still give the same result. If you want something else you need to define a criterion and decide what to do, the normal is this.

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));
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.