Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help rounding to 2 decimal places

Tags:

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.

like image 228
Steve B Avatar asked Aug 24 '12 16:08

Steve B


People also ask

What is the number 2.738 correct to 2 decimal places?

What is 2.738 Round to Two Decimal Places? In the given number 2.738, the digit at the thousandths place is 8, so we will add 1 to the hundredths place digit. So, 3+1=4. Therefore, the value of 2.738 round to two decimal places is 2.74.


1 Answers

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. decimal will do what you want:

Math.Round(0.575M, 2, MidpointRounding.AwayFromZero)

Result: 0.58

The 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.5749999999999999555910790149937383830547332763671875 You can see from this why rounding give 0.57.

like image 144
Chris Avatar answered Oct 20 '22 11:10

Chris