Reputation: 1035
The documentation states that the $end
of the range is inclusive. And this is the case most of the time, but when both $end
and $step
are floats, the last value is missing. Why is that?
print_r(range(1, 13, 1));
print_r(range(1, 13, 0.1));
print_r(range(0.1, 1.3, 0.1));
Output:
Array
(
[0] => 1
[1] => 2
// ...
[11] => 12
[12] => 13
)
Array
(
[0] => 0.1
[1] => 0.2
// ...
[119] => 12.9
[120] => 13
)
Array
(
[0] => 0.1
[1] => 0.2
// ...
[10] => 1.1
[11] => 1.2
// 12 => 1.3 is missing
)
Upvotes: 8
Views: 249
Reputation: 17598
The range is inclusive; however, your assumptions about the numbers adding up are incorrect.
0.1 cannot be represented in binary with exact precision. When you use it in a calculation in php, you'll actually get a number that's a little higher or lower. Take a look at the following codepad:
<?php
$sum = 1.0 + 0.1 + 0.1;
if ($sum > 1.2) {
print("1.2 > 1.2");
} else if ($sum < 1.2) {
print("1.2 < 1.2");
} else {
print("1.2 == 1.2");
}
Output:
1.2 > 1.2
Upvotes: 4