Possible Duplicate:
The accuracy of PHP float calculate
<?php
$foo = 0;
do {
echo "\$foo = $foo".($foo >= 0.8 ? " >= 0.8<br>\n" : " < 0.8<br>\n");
$foo = $foo + 0.1;
} while($foo <= 1);
?>
leads to the following output:
$foo = 0 < 0.8
$foo = 0.1 < 0.8
$foo = 0.2 < 0.8
$foo = 0.3 < 0.8
$foo = 0.4 < 0.8
$foo = 0.5 < 0.8
$foo = 0.6 < 0.8
$foo = 0.7 < 0.8
$foo = 0.8 < 0.8
$foo = 0.9 >= 0.8
$foo = 1 >= 0.8
.. even var_dump does not tell me more then it’s 0.8. Scary:
round($foo,1) >= 0.8
solves the problem – help appreciated!
To supplement the other answers:
produces
http://ideone.com/ggbMl
Go figure 😉
You could use round, depending on your case. But the typical solution is using the so called machine epsilon. Your condition then would be
The value of your EPS depends obviously on your platform but the value used in the condition also depends on the number of arithmetic operations you did on the number as each operation causes more rounding error. For more information read through the wiki article.