Home > Software engineering >  MidpointRounding in Math.Round not working correctly in C#
MidpointRounding in Math.Round not working correctly in C#

Time:11-21

The MidpointRound.AwayFromZero overload is supposed to round the 5 up in a rounding situation.

EX: Math.Round(1.5, 1, MidpointRounding.AwayFromZero);

This rounds 1.5 to 2.

However, when I try Math.Round(1.025, 2, MidpointRounding.AwayFromZero); it rounds it down to 1.02. It is supposed to round up to 1.03 though.

Does anyone have any idea why this is happening? Thanks!

CodePudding user response:

The value 1.025 cannot be represented exactly as the type double. Floating point numbers have that problem. See Why are floating point numbers inaccurate?.

When you write 1.025 as a double number, it will internally be a little bit smaller than 1.025. That's why the rounding delivers an unexpected value.

When dealing with money or other stuff where you want the value be exactly the same as displayed, use the type decimal instead of double:

decimal roundedValue = Math.Round(1.025m, 2, MidpointRounding.AwayFromZero);

Note that the m after the number turns the number into a literal of the decimal type.

  • Related