Random Float between 0 and 1 in PHP

How does one generate a random float between 0 and 1 in PHP?

I'm looking for the PHP's equivalent to Java's Math.random().


Solution 1:

You may use the standard function: lcg_value().

Here's another function given on the rand() docs:

// auxiliary function
// returns random number with flat distribution from 0 to 1
function random_0_1() 
{
    return (float)rand() / (float)getrandmax();
}

Solution 2:

Example from documentation :

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

Solution 3:

rand(0,1000)/1000 returns:
0.348 0.716 0.251 0.459 0.893 0.867 0.058 0.955 0.644 0.246 0.292

or use a bigger number if you want more digits after decimal point

Solution 4:

class SomeHelper
{
     /**
     * Generate random float number.
     *
     * @param float|int $min
     * @param float|int $max
     * @return float
     */
    public static function rand($min = 0, $max = 1)
    {
        return ($min + ($max - $min) * (mt_rand() / mt_getrandmax()));
    }
}

Solution 5:

update: forget this answer it doesnt work wit php -v > 5.3

What about

floatVal('0.'.rand(1, 9)); 

?

this works perfect for me, and it´s not only for 0 - 1 for example between 1.0 - 15.0

 floatVal(rand(1, 15).'.'.rand(1, 9));