Use PHP To Generate Random Decimal Beteween Two De

2019-03-22 19:55发布

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?

标签: php random
3条回答
放我归山
2楼-- · 2019-03-22 20:17

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);
查看更多
劳资没心,怎么记你
3楼-- · 2019-03-22 20:19

You can use:

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

or even better:

mt_rand ($min*10, $max*10) / 10
查看更多
时光不老,我们不散
4楼-- · 2019-03-22 20:26

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.

查看更多
登录 后发表回答