I got a problem with PHP. This exact substraction below is wrongly computed.
<?php
$test = 145.48 - 80.26;
if($test != 65.22)
echo 'not good !';
else
echo 'good';
?>
This echoes "not good" !!!
Why ?
I got a problem with PHP. This exact substraction below is wrongly computed.
<?php
$test = 145.48 - 80.26;
if($test != 65.22)
echo 'not good !';
else
echo 'good';
?>
This echoes "not good" !!!
Why ?
Computers aren't very good at storing floating point (decimal) numbers since representing a base 10 decimal number in binary is hard. For instance, if you try to store the number 0.2 in binary, the computer will store a series following the pattern 0.00110011… . Depending on the size of the floating point number (i.e. how many bits have been allocated for it in memory), the precision will vary, but more important, it will never accurately store exactly 0.2.
There are several ways to fix this, one is using the BC Math library and do something like:
bcsub("145.48", "80.26");
But sometimes the better solution is to just acknowledge that the numbers won't be accurate and account for the error, i.e.
if (abs($x - $y) < $e)
where e
is some very small number, e.g. 10^(-5). This is common practice when working with physics calculations and similar, but of course you should never attempt this when working with discrete numbers, e.g. currencies.
To do exact floating number arithmetic you can use bc_math
:
$test = bcsub("145.48", "80.26");
assert ($test == "65.22");