Try copying this code and past it to a new php file and see the result $total=1267.085; $rrr=85.100; $ppp=1181.985; $mmm=$total-$ppp-$rrr; echo"The value of mmm is $mmm ."; PHP: The value of $mmm is 1.4210854715202E-013 WHY AND HOW??????? It must be zero IF i change the forumal to $mmm=$total-$rrr-$ppp; it works correctly and the result will be zero Any idea what is the problem here?
I wonder if this is the issue with floating point precision, see: http://us.php.net/manual/en/language.types.float.php
1.4210854715202E-013 = 0.00000000000014210854715202 That is not very far off from 0. The problem is that computers work in binary, and just like 1/7 is impossible to write in decimal form in base 10 (decimal), so are some numbers in binary. Do you really need to be accurate to the ten-trillionth digit? Try just rounding it to 3 decimals with round()
yes, arbitrary precision is the way to go. Here's how you could use the bcmath class to do your calculations using bcsub(). Note the third parameter '3' rounds the number to the third decimal place. $total=1267.085; $rrr=85.100; $ppp=1181.985; $a = bcsub($total,$ppp,3); $mmm=$total-$ppp-$rrr; $mm2 = bcsub($a,$ppp,3); echo"The value of mmm is $mmm ."; echo "<br /> $mm2 is more accurate subtraction"; Code (markup):