-4

Possible Duplicate:
how to fix double precision issue in java

I have a small piece of code like this:

double number1 = 6;
double number2 = 5.99;
double result = number1 - number2;

However, the result == 0.009999999999999787 instead of 0.01

I know it is the issue of IEEE 754 standard, but I don't understand why. Could you please explain it for me?

Community
  • 1
  • 1
hungneox
  • 9,333
  • 12
  • 49
  • 66

2 Answers2

4

This is because float point numbers cannot be exactly represented with in binary system with limited bits (not without precision loss)

See: http://en.wikipedia.org/wiki/Loss_of_significance

sampson-chen
  • 45,805
  • 12
  • 84
  • 81
1

Because there is no .01 in floating point numbers. The fractional bits are expressed as 1/root 2 so you can get something like .0125 or what you have there but there is not .01 in floating point numbers. If you need exact precision use integers instead.

evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115