Why is this code not working?

・1 min read

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);
} 
DISCUSS (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:

$x = 8 - 6.4;  // which is equal to 1.6
$y = 1.6;
var_dump($x == $y); // is not true

PHP thinks that 1.6 (coming from a difference) is not equal to 1.6. To make it work, use round()

var_dump(round($x, 2) == round($y, 2)); // this is true

This happens probably because $x is not really 1.6, but 1.599999.. and var_dump shows it to you as being 1.6.

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:

<pre>
<?php

$test = 9.99;
print_r("test should be 9.99: $test\n");
if ($test == 9.99) {
    var_dump($test);
}

$test = $test + 30;
print_r("\ntest should be 39.99: $test\n");
if ($test == 39.99) {
    var_dump($test);
}

//$test = $test + 30.00;
$test = $test + 30;
print_r("\ntest should be 69.99: $test\n");

$notZero = $test - 69.99;
print_r("\n\$test - 69.99 should be 0?: \n" . $notZero);
// shows: 
// 1.4210854715202E-14
if ($test == 69.99) {
    var_dump($test);
}

// testing here too...
$test = $test + 10;
print_r("\ntest should be 79.99: $test<br/>");

if ($test == 79.99) {
    var_dump($test);
}
?>
</pre>
 

I didn't noticed that the subtraction throws those decimals, thanks for your answer.

Classic DEV Post from Aug 9 '18

What are some blockers for you on contributing to open source projects?

A discussion to understand some of the problems faced by the community on contributing to open source projects

Sore eyes?

dev.to now has dark mode.

Go to the "misc" section of your settings and select night theme ❤️

(There is also a pink mode)