Some strange things are going on in my code. Could someone explain please why is this condition false?
When I output object's members with php's function var_dump()
, I get this:
string(6) "105.63"
float(105.63)
from one object, and this is output from another object:
string(6) "667.69"
float(667.69)
Then I do comparison like this:
if(105.63 == "105.63"){
echo "true";
} else {
echo "false";
}
if(667.69 == "667.69"){
echo "true";
} else {
echo "false";
}
it outputs 2 times true
for sure, if we write code like in my example above. But in my class, it behaves differently. In first if
I get false
and in second if
I get true
. Then I looked to the data more deeply with var_export()
function and it seems like I actually have following data:
'105.63'
105.6300000000000096633812063373625278472900390625
and
'667.69'
667.69000000000005456968210637569427490234375
So I decide to check wether my conditions work with that data... And they dont. Actually, only first one doesn't. Why do I get output false
and true
in following code?
if(105.6300000000000096633812063373625278472900390625 == "105.63"){
echo "true";
} else {
echo "false";
}
if(667.69000000000005456968210637569427490234375 == "667.69"){
echo "true";
} else {
echo "false";
}
I know how to fix this. But I'm interested why conditions fails in first if
.
EDIT
Php does type juggling when we use ==
comparison operator!
Take a look at this:
var_export((float) "105.63");
var_export((string) 105.6300000000000096633812063373625278472900390625);
var_export((float) "667.69");
var_export((string) 667.69000000000005456968210637569427490234375);
outputs:
105.63
'105.63'
667.69000000000005
'667.69'
Should not this mean that the first condition be true and the second false? But I get false in first and true in second. Sorry if I was unclear.