DEV Community

Discussion on: Why is this code not working?

Collapse
 
alephnaught2tog profile image
Max Cerrina

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>
Collapse
 
dimitri_acosta profile image
Dimitri Acosta

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