5

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.

Zsolt Janes
  • 800
  • 2
  • 8
  • 26

3 Answers3

5

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";
}
Community
  • 1
  • 1
apokryfos
  • 38,771
  • 9
  • 70
  • 114
  • Thx for posting this answer even if there was one from me! And big thx for the refrence! Had a nearly similar problem some days ago, a bit mor complex and you just helped me to solve it. – Twinfriends Oct 20 '16 at 13:49
2

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
Twinfriends
  • 1,972
  • 1
  • 14
  • 34
0

You got your answer, that's great another way to achieve the same is as follows. Source

$start = 1;
$end = 1.3;
$place = 1;

$step = 1 / pow(10, $place);

for($i = $start, $k=0; $i <= $end; $i = round($i + $step, $place), $k += 25)
{
    echo $i . ' - ' . $k . '<br>';
}
Community
  • 1
  • 1
TIGER
  • 2,864
  • 5
  • 35
  • 45