Random float number between 0 and 1.0 php [duplicate]
mt_rand() / mt_getrandmax();
Avoid the rand()
function, since it usually depends on the platform's C rand()
implementation, generally creating numbers with a very simple pattern. See this comment on php.net
Update: In php 7.1 the rand()
has been changed and is now merely an alias of mt_rand()
. Therefore it is now ok to use rand()
, too.
What about simply dividing by 10?
$randomFloat = rand(0, 10) / 10;var_dump($randomFloat);//eg. float(0.7)
$v = mt_rand() / mt_getrandmax();
will do that.
In case you want only one decimal place (as in the examples from the question) just round()
the value you get...
$v = round( $v, 1 );
...or calculate a number between 0 and 10 and divide by 10:
$v = mt_rand( 0, 10 ) / 10;