Reputation: 115
<?php
echo 199.8 + 0.9 -200.7; //expect 0, result 2.8421709430404E-14 ?
?>
Tested on PHP Version 5.3.2-1 ubuntu4.7
Upvotes: 0
Views: 1301
Reputation: 11020
Here some exact example with http://www.php.net/manual/en/ref.bc.php:
<?php
$a = 199.8;
$b = 0.9;
$c = 200.7;
// set precision
bcscale(1);
$ab = bcadd($a, $b);
echo bcsub($ab, $c); // result 0.0
?>
Tested with PHP 5.3.3-7+squeeze1 on Debian Squeeze
Upvotes: 0
Reputation: 12850
If you want exact calculations (ie. for monetary transactions) you should use BCD (binary coded decimals) or arbitrary precision math. PHP has support for this using BC Math.
Upvotes: 2
Reputation: 385144
Space-limited, fractional floating point is inaccurate for some values (just in the same way that, in decimal notation, you cannot write out 1/3
in finite space).
2.8421709430404E-14
is very close to 0.
Round it, or output it to a certain number of significant figures.
Upvotes: 7