7
votes

I want to create random number between two decimal numbers with step 0.5.

Examples: 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, ...

Use PHP To Generate Random Decimal Beteween Two Decimals

So far I can generate numbers between 0 and 5 with one decimal comma.

How to integrate step 0.5?

$min = 0;
$max = 5;
$number = mt_rand ($min * 10, $max * 10) / 10;
3
why not just mt_rand($min+$step, $max-$step) + $step? - Marc B
I'm not sure I understand what you want. do you mean pick randomly the numbers between min and max with step 0.5? ie one of the numbers of your list? - 1010
@MarcB if the step is 0.5 output will be x.5 - Shaiful Islam

3 Answers

7
votes

This should work for you:

$min = 0;
$max = 5;
echo $number = mt_rand($min * 2, $max * 2) / 2;
1
votes

Another possible way:

function decimalRand($iMin, $iMax, $fSteps = 0.5)
{
    $a = range($iMin, $iMax, $fSteps);

    return $a[mt_rand(0, count($a)-1)];
}
1
votes

More intuitive, less unnecessary actions:

$min = 0;
$max = 5;
$step = 0.5;
// Simple for the case above.
echo $number = mt_rand($min * 2, $max * 2) * $step;

More general, a bit sophisticated case

echo $number = mt_rand(floor($min / $step), floor($max / $step)) * $step;

mt_rand offical docs just in case.