-6
double sth = 250 - 249.99;
Console.WriteLine(sth);

Why does this return sth like 0.009994507, instead of 0.01?

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215

3 Answers3

1

Floating point numbers (in this case doubles) cannot represent decimal values exactly. For more info, see this page here

If you need a more accurate representation, use decimal instead.

parameter
  • 614
  • 10
  • 17
0

because when you print the double you print the all double value not just the first x after point digits.

you can use String.Format to print only the first 2 numbers.

        double sth = 250.00d - 249.99d;
        string sthString = String.Format("{0:0.00}", sth);
        Console.WriteLine(sthString);
0

There are a lot of decimals that have infinite binary representation. What you're experiencing is exactly this case.

For more on this topic see: http://www.exploringbinary.com/why-0-point-1-does-not-exist-in-floating-point/

MartinPtrl
  • 71
  • 2
  • 8