2012-05-02 52 views
18

我需要生成一個隨機數,到PHP中2位小數之間的第10個點。使用PHP來產生兩個小數之間的隨機十進制

Ex。 1.2到5.7之間的一個數字。它會返回3.4

我該怎麼做?

+0

這是愚蠢的,但我需要的功能。如下: function drand($ low,$ high){ \t \t return mt_rand($ low * 100,$ high * 100)/ 100; \t} –

回答

34

分裂所產生的隨機數,你可以使用:

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

甚至更​​好:

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

你可以這樣做:

rand(12, 57)/10 

PHP的隨機函數允許你只使用整數的限制,但你可以通過10

5

一個更普遍的解決辦法是:

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

對於那些追求這種解決方案的人來說,現在稍微好一點的方法是將'count_decimals()'函數嵌入'random()'中作爲閉包,所以它對全局作用域是隱藏的。 – igorsantos07