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;
The rand() function generates a random integer. Example tip: If you want a random integer between 10 and 100 (inclusive), use rand (10,100). Tip: As of PHP 7.1, the rand() function has been an alias of the mt_rand() function.
Generate a random decimal within a specified rangeEnter the formula =RAND()*([UpperLimit]-[LowerLimit])+[LowerLimit]. For example, if you'd like to generate a random decimal between one and 10, you may enter =RAND()*(10-1)+1. Press the "Enter" key.
Definition and Usage. The mt_rand() function generates a random integer using the Mersenne Twister algorithm. Example tip: If you want a random integer between 10 and 100 (inclusive), use mt_rand (10,100).
Use a random. random() function of a random module to generate a random float number uniformly in the semi-open range [0.0, 1.0) . Note: A random() function can only provide float numbers between 0.1. to 1.0. Us uniform() method to generate a random float number between any two numbers.
This should work for you:
$min = 0;
$max = 5;
echo $number = mt_rand($min * 2, $max * 2) / 2;
Another possible way:
function decimalRand($iMin, $iMax, $fSteps = 0.5)
{
$a = range($iMin, $iMax, $fSteps);
return $a[mt_rand(0, count($a)-1)];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With