A few days ago I saw someone asking why this code is not reaching the third var_dump
, so I tried to execute this in my computer, with all the different versions of PHP available and it is not working on any of them so, what's going on here?
I've tried changing the code in many ways and it never reaches the third var_dump
, it's driving me crazy
<?php
$test = 9.99;
if ($test == 9.99) {
var_dump($test);
}
$test = $test + 30;
if ($test == 39.99) {
var_dump($test);
}
$test = $test + 30;
if ($test == 69.99) {
var_dump($test);
}
Top comments (4)
Hmm, don't know PHP but it might be something to do with floats (numbers that have really long decimal places). Basically, when you do some math to a number that involves a decimal place, there's usually some weird precision going under the hood.
Gonna paste in this excellent answer by catalin dot luntraru that I found from the PHP docs:
And with your example, comparing the rounded numbers will hit the final
if
statement:This is kinda awkward because now I'm not sure if I can rely on my code
Floating point arithmetic!
This shows it nicely:
I didn't noticed that the subtraction throws those decimals, thanks for your answer.