1

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

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
  • 2
    This question already has a good answer here (You're using a double, which isn't as precise as you think in this situation): https://stackoverflow.com/questions/9221205/why-does-system-midpointrounding-awayfromzero-not-round-up-in-this-instance – Pepper Paige May 29 '22 at 00:39
  • 1
    See also https://stackoverflow.com/questions/588004/is-floating-point-math-broken – Charlieface May 29 '22 at 02:12

2 Answers2

3

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);
leejulee
  • 106
  • 5
1

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.

Salix alba
  • 7,536
  • 2
  • 32
  • 38