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!
The value
1.025cannot be represented exactly as the typedouble. Floating point numbers have that problem. See Why are floating point numbers inaccurate?.When you write
1.025as adoublenumber, it will internally be a little bit smaller than1.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
decimalinstead ofdouble:Note that the
mafter the number turns the number into a literal of thedecimaltype.