-1

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.

Atlantiz8
  • 65
  • 1
  • 2
  • 11
  • you should check on this https://msdn.microsoft.com/en-us/library/system.midpointrounding(v=vs.110).aspx – Nic Sep 08 '15 at 03:31
  • For the down vote is not i vote. You might need to round up 3 precision first then round up 2 precision. double a = 39.3;double b = 0.95;Response.Write(Math.Round(Math.Round(a * b, 3),2)); – Nic Sep 08 '15 at 03:44
  • Thanks for the suggestion. I could be lucky in this case because I'd never know exactly how many precision I have to round first, before I can round it back to 2. At the moment I just ToString() and parse it back to double it seems resolve the problem. But I'd really like to know why and any better/proper resolving method. – Atlantiz8 Sep 08 '15 at 03:47

1 Answers1

0

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.

Atlantiz8
  • 65
  • 1
  • 2
  • 11