For some reason, PHP decided that if:
$a = "3.14159265358979326666666666"
$b = "3.14159265358979323846264338"
$a == $b
is true.
Why is that, and how can I fix that?
It ruins my code.
For some reason, PHP decided that if:
$a = "3.14159265358979326666666666"
$b = "3.14159265358979323846264338"
$a == $b
is true.
Why is that, and how can I fix that?
It ruins my code.
PHP converts strings (if possible) to numbers (source). Floating points have a limited precision (source). So $a == $b
because of rounding errors.
Use ===
or !==
.
<?php
$a = "3.14159265358979326666666666";
$b = "3.14159265358979323846264338";
if ($a == $b) {
echo "'$a' and '$b' are equal with ==.<br/>";
} else {
echo "'$a' and '$b' are NOT equal with ==.<br/>";
}
if ($a === $b) {
echo "'$a' and '$b' are equal with ===.<br/>";
} else {
echo "'$a' and '$b' are NOT equal with ===.<br/>";
}
?>
Results in
'3.14159265358979326666666666' and '3.14159265358979323846264338' are equal with ==.
'3.14159265358979326666666666' and '3.14159265358979323846264338' are NOT equal with ===.
When you want to do high precision mathematics, you should take a look at BC Math.
You could use ===
in the equality test.
$a = "3.14159265358979326666666666";
$b = "3.14159265358979323846264338";
if($a===$b)
{
echo "ok";
}
else
{
echo "nope";
}
This code will echo nope
.
Comparing with ==
is a loose comparison, and both strings will be converted to numbers, and not compared right away.
Using ===
will perform a string comparison, without type conversion, and will give you the wanted result.
You can find more explanations in the PHP manual:
Read PHP: Comparison Operators
If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. These rules also apply to the switch statement. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.
Others have recommended BC Math, but if you are doing floating point comparisons, the traditional way of comparing numbers is to see if they are the same to a reasonable error level
$epsilon = 1.0e-10;
if (abs($a - $b) < $epsilon) then {
// they're the same for all practical purposes
}
Try using $a === $b
instead; you should never use ==
for string comparison.
You should not to compare a float variable like that.
Try this:
bccomp($a, $b, 26)