Why is it that when I do the following…
Math.Round(0.75, 1, MidpointRounding.AwayFromZero)
I get 0.8
but when I do the following…
Math.Round(0.575, 2, MidpointRounding.AwayFromZero)
I don’t get 0.58. Instead I get 0.57. I want anything that is 5 and up rounding up, so 0.575 should be 0.58.
The problem will be that you cannot represent 0.575 exactly as a binary floating point number (eg a double). Though I don’t know exactly it seems that the representation closest is probably just a bit lower and so when rounding it uses the true representation and rounds down.
If you want to avoid this problem then use a more appropriate data type.
decimalwill do what you want:Result:
0.58The reason that 0.75 does the right thing is that it is easy to represent in binary floating point since it is simple 1/2 + 1/4 (ie 2^-1 +2^-2). In general any finite sum of powers of two can be represented in binary floating point. Exceptions are when your powers of 2 span too great a range (eg 2^100+2 is not exactly representable).
Edit to add:
Formatting doubles for output in C# might be of interest in terms of understanding why its so hard to understand that 0.575 is not really 0.575. The DoubleConverter in the accepted answer will show that 0.575 as an Exact String is
0.5749999999999999555910790149937383830547332763671875You can see from this why rounding give 0.57.