I need to generate a random number, to the 10th spot between 2 decimals in PHP.
Ex. A rand number between 1.2 and 5.7. It would return 3.4
How can I do this?
You can use:
rand ($min*10, $max*10) / 10
or even better:
mt_rand ($min*10, $max*10) / 10
You could do something like:
rand(12, 57) / 10
PHP's random function allows you to only use integer limits, but you can then divide the resulting random number by 10.
A more general solution would be:
function count_decimals($x){
return strlen(substr(strrchr($x+"", "."), 1));
}
public function random($min, $max){
$decimals = max(count_decimals($min), count_decimals($max));
$factor = pow(10, $decimals);
return rand($min*$factor, $max*$factor) / $factor;
}
$answer = random(1.2, 5.7);
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