我需要生成一个随机数,到 PHP 中小数点 2 位之间的第 10 位。
前任。介于 1.2 和 5.7 之间的兰特数。它将返回 3.4
我该怎么做?
您可以使用:
rand ($min*10, $max*10) / 10
甚至更好:
mt_rand ($min*10, $max*10) / 10
你可以做这样的事情:
rand(12, 57) / 10
PHP 的随机函数允许您仅使用整数限制,但您可以将生成的随机数除以 10。
更通用的解决方案是:
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);
如果你想作为函数
/**
* @param float $min
* @param float $max
* @param int $digit
* @return float|int
*/
public function randomDecimal(float $min, float $max, int $digit = 2): float|int
{
return mt_rand($min * 10, $max * 10) / pow(10, $digit);
}