I'm trying to increment decimal places on php but it doesn't break inside the if statement
for($x = 0; $x <= 1; $x += 0.001){
//0.01 = 0.010
if($x===0.01){
break;
}
echo $x.'<br>';
}
I'm trying to increment decimal places on php but it doesn't break inside the if statement
for($x = 0; $x <= 1; $x += 0.001){
//0.01 = 0.010
if($x===0.01){
break;
}
echo $x.'<br>';
}
Floating point arithmetic is not exact in PHP (or really any language). Read Is floating point math broken for a general explanation of why this is the case.
As a result, the loop counter might not ever have the exact value 0.01
. Instead, you could break when the dummy variable has exceeded a threshold of 0.01
:
for ($x=0; $x <= 1; $x += 0.001) {
// 0.01 = 0.010
if ($x >= 0.01) {
break;
}
echo $x . '<br>';
}
When tested locally, the above script is printing:
0<br>0.001<br>0.002<br>0.003<br>0.004<br>0.005<br>0.006<br>0.007<br>0.008<br>0.009<br>