c# double multiply gets additional precision

471 Views Asked by At

after multiplying 2 double, it gets so many additional precision. Then it causes rounding(to 2 decimal) issue. Where I'm suppose to get 37.34, but it gives 37.33 instead. (viewing in debug mode)

additional precision http://s8.postimg.org/9nn2bbiab/precision.jpg

Any idea why? and how to solve?

EDIT

I actually did tried the MidpointRounding. Try this on Any calculator it should give you exactly 37.335 But C# gave me 37.334999999999, which later result in wrong answer after rounding with 2 decimal.

still rounded wrongly http://s28.postimg.org/psi2dz59n/precision2.jpg

The problem I believe was not on the rounding, but the multiplying.

1

There are 1 best solutions below

0
Atlantiz8 On

Before I understand why could this happen. I got myself a workaround, probably could help others in case they're having the same problem. It looks dirty anyway.

double price = 39.3;
double m = 0.95;

double result = 39.3 * 0.95;
result = double.Parse(result.ToString());

result = Math.Round(result, 2, MidpointRounding.AwayFromZero);

This way I'll get 37.335 after multiplying, and I got 37.34 after rounding to 2 decimal.