I received an error in a condition where I need a substraction result to be less or equal to zero. The specific values are (obtained via var_dump):
$arr_charges[total] = float(25.63)
$arr_credits[total] = float(25.63)
($arr_charges[total] - $arr_credits[total]) = float(3.5527136788005E-15)
I would expect ($arr_charges[total] - $arr_credits[total]) = float(0)
, because both values are the same number. I understand this issue can happen with different numbers, due to the precision problem with float numbers, but I think this is strange when the same number is used as minuend and subtrahend.
I'm using PHP:
> php --version
PHP 5.4.6-1ubuntu1.8 (cli) (built: Apr 4 2014 01:28:36)
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2012 Zend Technologies
with XCache v2.0.0, Copyright (c) 2005-2012, by mOo
Is this normal? or is this a PHP bug?
There seems to be a way to fix the result, and that is to apply a cast to int
. In my case it works, but that might be not enough in some cases.
UPDATE 05/01/2014 - 1
Thanks for your kind answers. Here is a piece of code related:
$arr_charges['total'] = 25.63;
$arr_credits['total'] = 25.63;
return (($arr_charges['total'] - $arr_credits['total']) <= 0 );
This code is returning false, because the substraction operation returns 3.5527136788005E-15
, as explained above in the var_dump results.
Yes, I know there is an issue with floating point precision, but I wouldn't expect that issue to happen in a case like the exposed above. Even so, I ask because I would like to know if there is serious a way to use this kind of operations with floating point values.
Thanks.