-1

Possible Duplicate:
Floating point inaccuracy examples
PHP rounding issue - Is this a bug?

Found what may be a bug in PHP, but I wanted to check to see if it's just some weird calculation or something that someone already knows about.

An example:

$available = 64.02;
$spent = 64.01;
$available -= $spent;
print $available."<br />";

I'd expect the result to be 0.01, right? However, I get 0.00999999999999.

If you do this for any integer less than 64 (ex: 45.02 - 45.01) I get the correct 0.01 result. Anything greater than or equal to 64, however, gives me 0.00999999999999.

I've tested in PHP 5.2.17 and PHP 5.2.12. Tried to google it, but couldn't find anything. Can any one shed any light on this issue?

Community
  • 1
  • 1
Charlie
  • 323
  • 2
  • 12
  • 4
    This isn't a bug, it's an expected behaviour of [floating point](http://stackoverflow.com/questions/2100490/floating-point-inaccuracy-examples) numbers. Possible duplicate of [PHP rounding issue - Is this a bug?](http://stackoverflow.com/questions/6441548/php-rounding-issue-is-this-a-bug) – user229044 Feb 08 '12 at 23:04
  • 1
    Don't make us launch into a discussion about how .00999999... = .01 ;-) – Tim Feb 08 '12 at 23:08

1 Answers1

1

This is typical of floating point arithmetic. These numbers are stored in binary and there is not always an exact representation of every number in binary. The same problem can be observed in base ten when you try to represent 1/3 and you end up with an endless decimal sequence whereas the the same number represented in a base that is a multiple of three would have a finite sequence.

This shouldn't be a big problem, anyways, 0.00999999999999 is only 0.00000000000001 different than 0.01.

Peter Olson
  • 139,199
  • 49
  • 202
  • 242
  • Thanks. Wasn't a big problem, just rounded the resulting number, but I was curious as to the reason for it. I thought there was probably a reason for it, I just couldn't find one (Google doesn't exactly know what to do with ".02 - .01 equals 0.00999999999999 in PHP"). – Charlie Feb 09 '12 at 00:19