Search code examples
c#mathmath.round

Issue with Math.Round for decimals shows incorrect rounding


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


Solution

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