I want to compare two floats in PHP, like in this sample code:
$a = 0.17;
$b = 1 - 0.83; //0.17
if($a == $b ){
echo 'a and b are same';
}
else {
echo 'a and b are not same';
}
In this code it returns the result of the else
condition instead of the if
condition, even though $a
and $b
are same. Is there any special way to handle/compare floats in PHP?
If yes then please help me to solve this issue.
Or is there a problem with my server config?
If you do it like this they should be the same. But note that a characteristic of floating-point values is that calculations which seem to result in the same value do not need to actually be identical. So if
$a
is a literal.17
and$b
arrives there through a calculation it can well be that they are different, albeit both display the same value.Usually you never compare floating-point values for equality like this, you need to use a smallest acceptable difference:
Something like that.
If you have a small, finite number of decimal points that will be acceptable, the following works nicely (albeit with slower performance than the epsilon solution):
I hate to say it, but "works for me":
Now, floating point comparisons are in general tricky - things that you might expect to be the same are not (due to rounding errors and/or representation nuances). You might want to read http://floating-point-gui.de/
This works for me on PHP 5.3.27.
I ended simply with: