[ACCEPTED]-Need help rounding to 2 decimal places-math-functions

Accepted answer
Score: 36

The problem will be that you cannot represent 22 0.575 exactly as a binary floating point 21 number (eg a double). Though I don't know 20 exactly it seems that the representation 19 closest is probably just a bit lower and 18 so when rounding it uses the true representation 17 and rounds down.

If you want to avoid this 16 problem then use a more appropriate data 15 type. decimal will do what you want:

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

Result: 0.58

The 14 reason that 0.75 does the right thing is 13 that it is easy to represent in binary floating 12 point since it is simple 1/2 + 1/4 (ie 2^-1 11 +2^-2). In general any finite sum of powers 10 of two can be represented in binary floating 9 point. Exceptions are when your powers of 8 2 span too great a range (eg 2^100+2 is 7 not exactly representable).

Edit to add:

Formatting doubles for output in C# might 6 be of interest in terms of understanding 5 why its so hard to understand that 0.575 4 is not really 0.575. The DoubleConverter 3 in the accepted answer will show that 0.575 2 as an Exact String is 0.5749999999999999555910790149937383830547332763671875 You can see from 1 this why rounding give 0.57.

Score: 9

The System.Math.Round method uses the Double structure, which, as 6 others have pointed out, is prone to floating 5 point precision errors. The simple solution 4 I found to this problem when I encountered 3 it was to use the System.Decimal.Round method, which doesn't 2 suffer from the same problem and doesn't 1 require redifining your variables as decimals:

Decimal.Round(0.575, 2, MidpointRounding.AwayFromZero)

Result: 0.58

Score: 2

It is caused by a lack of precision with 16 doubles / decimals (i.e. - the function 15 will not always give the result you expect).

See 14 the following link: MSDN on Math.Round

Here is the relevant 13 quote:

Because of the loss of precision that 12 can result from representing decimal values 11 as floating-point numbers or performing 10 arithmetic operations on floating-point 9 values, in some cases the Round(Double, Int32, MidpointRounding) method 8 may not appear to round midpoint values 7 as specified by the mode parameter.This 6 is illustrated in the following example, where 5 2.135 is rounded to 2.13 instead of 2.14.This 4 occurs because internally the method multiplies 3 value by 10digits, and the multiplication 2 operation in this case suffers from a loss 1 of precision.

More Related questions