Issue with Math.Round for decimals shows incorrect rounding

951 Views Asked by At

I am getting invalid value when performing this Math.Round(0.575, 2, MidpointRounding.AwayFromZero)

trying to do midpoint rounding up?

Input: Math.Round(0.575, 2, MidpointRounding.AwayFromZero) Expected: 0.58 but getting 0.57

Input: Math.Round(-0.575, 2, MidpointRounding.AwayFromZero) Expected: -0.58 but getting -0.57

Input: Math.Round(-0.865, 2, MidpointRounding.AwayFromZero) Expected: -0.87 and the output matches the expected result as -0.87

Here is the quick fiddle to try https://dotnetfiddle.net/KdR8pN

2

There are 2 best solutions below

1
leejulee On BEST ANSWER

Can you try to use decimal type instead of double type? thanks.

example: https://learn.microsoft.com/en-us/dotnet/api/system.math.round?view=net-6.0#system-math-round(system-decimal-system-midpointrounding)

Decimal targetValue = -0.575m;
Decimal targetValue1 = 0.575m;
    
Console.Write(Math.Round(targetValue, 2, MidpointRounding.AwayFromZero) + Environment.NewLine);
Console.Write(Math.Round(targetValue1, 2, MidpointRounding.AwayFromZero)+ Environment.NewLine);
0
Salix alba On

Have a look at Why is 0.575 * 100 not same as 57.5?.

The problem is that 0.575 cannot be exactly represented as a floating point number, instead the nearest floating point number 0.57499999999999996 is used. Hence, it will always round down to 0.57.