Bach Bach - 5 months ago 9
PHP Question

PHP - Comparing double to a string is weird?

I'm seeing some weird behavior in php when comparing a double to a string and was hoping someone could explain to me what is going on.

If I declare $num = 0.333;
and then test
$num == '0.333',
this comes out as true. If I then add 1 to $num and then subtract 1, then $num == '0.333' comes out as false. If I then cast $num as a string, the comparison goes back to being true. Why is it doing this?

Here's a sample:

<?php
$num = 0.333;

//returns 0.333 double Yes
echo $num, ' ', gettype($num), ' ', $num == '0.333' ? 'Yes' : 'No', '<br />';

$num += 1;
$num = $num - 1;

//returns 0.333 double No
echo $num, ' ', gettype($num), ' ', $num == '0.333' ? 'Yes' : 'No', '<br />';

$str = (string)$num;

//returns 0.333 string Yes
echo $str, ' ', gettype($str), ' ', $str == '0.333' ? 'Yes' : 'No', '<br />';
?>


Thanks.

Answer

You are comparing a floating point.

http://php.net/manual/en/language.types.float.php says:

never compare floating point numbers for equality.

The == compares for value, but 'across' types: one of the types must be converted before it can actually be compared. And this will result in comparison of floating point variables. That's why after doing a seemingly balanced action (+1 and -1) you're getting different results.

Comments