Reputation: 5612
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;
Upvotes: 10
Views: 5871
Reputation: 7800
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.
Upvotes: 1
Reputation: 821
Another possible way:
function decimalRand($iMin, $iMax, $fSteps = 0.5)
{
$a = range($iMin, $iMax, $fSteps);
return $a[mt_rand(0, count($a)-1)];
}
Upvotes: 1
Reputation: 59681
This should work for you:
$min = 0;
$max = 5;
echo $number = mt_rand($min * 2, $max * 2) / 2;
Upvotes: 10