Php invalid string equality

For some reason, PHP decided that if:

$a = "3.14159265358979326666666666" $b = "3.14159265358979323846264338" 

$a == $b true.

Why is this and how can I fix it? This breaks my code.

+6
source share
5 answers

Problem

PHP converts strings (if possible) to numbers ( source ). Floating points have limited accuracy ( source ). Therefore, $a == $b due to rounding errors.

Correction

Use === or !== .

Try

 <?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 ===. 

Note

If you want to do the math with high precision, you should take a look at BC Math .

+6
source

You can 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 free comparison, and both strings will be converted to numbers and will not be compared immediately.

Using === will perform string comparisons without type conversion and give you the desired result.

For more information on the PHP manual, see the following articles:

+4
source

Read PHP: Comparison Operators

If you are comparing a number with a string or comparing numeric strings, then each string is converted to a number and the comparison is performed numerically. These rules also apply to switch expression. Type conversion does not occur when the comparison is === or! ==, as this involves a type comparison as well as a value.

Others have recommended BC Math, but if you are making floating point comparisons, the traditional way of comparing numbers is to determine if they match a reasonable level of error

 $epsilon = 1.0e-10; if (abs($a - $b) < $epsilon) then { // they're the same for all practical purposes } 
+1
source

Try using $a === $b instead; you should never use == to compare strings.

+1
source

You should not compare float var. Try the following:

 bccomp($a, $b, 26) 
+1
source

All Articles