前言
PHP本身并沒有在指定范圍內(nèi)生成隨機(jī)小數(shù)的函數(shù), 但是這種場景會在很多地方用到
只能我們自己去實現(xiàn)這種算法, 本文記錄使用PHP生成在指定范圍內(nèi)的隨機(jī)小數(shù)算法幾種方法
方案一:mt_rand() / mt_getrandmax()
/**
* 生成隨機(jī)小數(shù)
*/
function randFloat($min, $max)
{
if ($min >= $max) {
throw new \Exception('最大值必須大于最小值', 501);
}
$rand = $min + mt_rand() / mt_getrandmax() * ($max - $min);
return floatval(sprintf('%.2f', $rand));
}