I have the following php for loop
$screen = 1.3; // it can be other decimal value
for ($i = 1, $k = 0; $i <= $screen; $i += 0.1, $k+=25) {
echo $i . ' - ' . $k . '<br>';
}
It works fine but i would like to run the for loop til 1.3 - 75 now it print me 1.2 - 50. I try to change $i <= $screen to $i = $screen but it does not work.
If you read http://php.net/manual/en/language.types.float.php there's a nice statement you should keep in mind:
Testing floating point values for equality is problematic, due to the way that they are represented internally
To test floating point values for equality, an upper bound on the relative error due to rounding is used. This value is known as the machine epsilon, or unit roundoff, and is the smallest acceptable difference in calculations.
Based on the recommendation there you need to do something like :
<?php
$screen = 1.3; // it can be other decimal value
$epsilon=0.0001;
for ($i = 1, $k = 0; $i <= $screen+$epsilon; $i += 0.1, $k+=25) {
echo $i . ' - ' . $k . "\n";
}
Two solutions:
$screen = 1.4; // it can be other decimal value
for ($i = 1, $k = 0; $i <= $screen; $i += 0.1, $k+=25) {
echo $i . ' - ' . $k . '<br>';
}
OR:
$screen = 1.3; // it can be other decimal value
for ($i = 1, $k = 0; $i <= $screen+0.1; $i += 0.1, $k+=25) {
echo $i . ' - ' . $k . '<br>';
}
Tested. Both work... as far i have understand what you want to do.
Tested Output of both:
1 - 0
1.1 - 25
1.2 - 50
1.3 - 75
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With