Compare floats in php
Read the red warning in the manual first. You must never compare floats for equality. You should use the epsilon technique.
For example:
if (abs($a-$b) < PHP_FLOAT_EPSILON) { … }
where PHP_FLOAT_EPSILON
is constant representing a very small number (you have to define it in old versions of PHP before 7.2)
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:
if (abs(($a-$b)/$b) < 0.00001) {
echo "same";
}
Something like that.
Or try to use bc math functions:
<?php
$a = 0.17;
$b = 1 - 0.83; //0.17
echo "$a == $b (core comp oper): ", var_dump($a==$b);
echo "$a == $b (with bc func) : ", var_dump( bccomp($a, $b, 3)==0 );
Result:
0.17 == 0.17 (core comp oper): bool(false)
0.17 == 0.17 (with bc func) : bool(true)