PHP how to use range() for float numbers
488
Is there a way to use PHPrange()
for a really small number? like below?
range(0.54,0.58);
Doing this creates an error.
range(): step exceeds the specified range in
Answer
Solution:
The third parameter is the
step
.Reading the documentation is a very good place to start.
If you read you will see that you can set the step to something that can increment between your limits.
The error message is simply telling you that it cannot increment 0.54 by 1 without going over 0.58 - think about, it 1 + 0.54 is more than 0.58!
Using this line instead will give you the desired output.
Answer
Solution:
The error message is self-explanatory: the default value of
{-code-1}
(the third argument of) is
1
and using it produces an empty range.Provide a third argument to
. From the value of
$start
and$end
I think0.01
is the step you need:Check it out: https://3v4l.org/IcUAh
Answer
Solution:
You should also provide the range you want.
Like this
var_dump(range(0.54,0.58,0.01));
output is
Answer
Solution:
use the third parameter to set a step
range(0.54,0.58, 0.01);
or you could multiply your values by 1000 and then divide by 1000 which would be silly...
Answer
Solution:
The other answers here did not work for me as, due to rounding error with floats, the result is not exact:
Examples:
php 7.4: (inclusive vs. exclusive)
php 8.0: (inclusive vs. exclusive + rounding errors)
Solution:
This does give my expected result (PHP 7.4 and up):