Generating a float random value in PHP is a little bit tricky. Both rand() and mt_rand() will return an integer value. But sometimes you need to generate a random float value, for currency or math cases for example. So I would like to share my little script to generate a float random value.
/**
* Generate Float Random Number
*
* @param float $Min Minimal value
* @param float $Max Maximal value
* @param int $round The optional number of decimal digits to round to. default 0 means not round
* @return float Random float value
*/
function float_rand($Min, $Max, $round=0){
//validate input
if ($min>$Max) { $min=$Max; $max=$Min; }
else { $min=$Min; $max=$Max; }
$randomfloat = $min + mt_rand() / mt_getrandmax() * ($max - $min);
if($round>0)
$randomfloat = round($randomfloat,$round);
return $randomfloat;
}
Usage:
float_rand(0.01,5.00); //Generate float value with no rounding
float_rand(0.01,5.00,2); //Generate float value rounded to 2 decimals
This code is free to use in any PHP application you like. If you like it, please leave me any comments — I really appreciate it.
