Why is this code not working?

Dimitri Acosta on May 28, 2018

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 dif... [Read Full]
markdown guide
 

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.

code of conduct - report abuse