2016-11-30 51 views
0
$a = floatval(0.0001); 
$b = floatval(0.0009); 
$c = rand($a,$b); // int(0); 

我怎樣才能從$a$b花車蘭特?
$ a和$b的乘法不是解決方案,因爲我不知道點號後的位數。PHP我如何提供浮動值?

+0

$ a和$ b的加法? – MVCNoob

回答

2

this article

一種優雅的方式返回兩個數字之間的隨機浮動:

function random_float ($min,$max) { 
    return ($min+lcg_value()*(abs($max-$min))); 
} 
+0

謝謝!這只是我想要的 –

0

您可以創建具有隨機值高於0,devide它。

$a = 1; 
$b = 9; 
$c = rand($a, $b); 
$c = $c/10000; 
0

另一種解決方法是計數的小數位數,並做搭載該號碼數字的rand

function count_decimals($x) { 
    return strlen(substr(strrchr($x+"", "."), 1)); 
} 

function random($min, $max, $precision = 0) { 
    $decimals = max(count_decimals($min), count_decimals($max)) + $precision; 
    $factor = pow(10, $decimals); 
    return rand($min*$factor, $max*$factor)/$factor; 
} 

var_dump(random(0.001, 0.009)); // 0.004 
var_dump(random(0.001, 0.009, 1)); // 0.0046 
var_dump(random(0.001, 0.009, 2)); // 0.00458 
var_dump(random(0.001, 0.009, 5)); // 0.00458014 

我加入了$precision參數,所以你可以選擇多少小數你想追加你的隨機數。