-6
double a=60.5;
double a=60.1;

Console.WriteLine(a-b);

Return value is 0.399999999999999 not 0.4

nadun
  • 393
  • 1
  • 4
  • 14
Majed Maniat
  • 11
  • 2
  • 5
  • 5
    Is there some reason why the seven and a half million *other* questions on SO about floating point imprecision didn't satisfy your curiosity? :-) – paxdiablo Dec 23 '16 at 05:17
  • 3
    @paxdiablo: I'm guessing there were actually only 7499999 other questions and this was the one missing... – user541686 Dec 23 '16 at 05:18
  • Have a look at this link:http://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate – Praburaj Dec 23 '16 at 05:19

1 Answers1

3

It is because you use double: double is floating point, which is not precise; decimal, on the other hand, is precise. If you change both variable to decimal, it will be the exact number.

That is why in certain domains, like financial industry, decimal is desired for accuracy and precision.

  • 4
    This is not accurate. `Decimal` is floating-point too. The big difference is that `float` is base-2 and thus can only approximate base-10 numbers, while `Decimal` is base-10 which removes any errors due to simple approximation. It is still vulnerable to precision errors if used unwisely. – Cory Nelson Dec 23 '16 at 05:29
  • Doubles *are* precise in that they have precision. What they *don't* have is infinite precision. Something else that doesn't have infinite precision is Decimals :-) No encoding method (other than actual symbolics) can handle all cases, such as `√2`, `π`, `e`, or `⅓` - these will all cause precision loss for Decimal type. See also http://stackoverflow.com/questions/8270789/what-is-the-difference-between-precision-and-accuracy/8270869#8270869. – paxdiablo Dec 23 '16 at 08:10