Use PHP To Generate Random Decimal Beteween Two De

2019-03-22 19:43发布

问题:

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?

回答1:

You can use:

rand ($min*10, $max*10) / 10

or even better:

mt_rand ($min*10, $max*10) / 10


回答2:

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.



回答3:

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);


标签: php random