Random Float between 0 and 1 in PHP

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();
}

Example from documentation :

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

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()));
    }
}

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

Tags:

Php

Random