PHP Snippet Code To Generate Random Float Number

Generating a float random value in PHP is little bit tricky. Both rand() and mt_rand() will return Integer value. But sometimes you need to generate random float value, for currency or math case for examples. 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 rounded
float_rand(0.01,5.00,2);  //Generate float value with rounded to 2 decimals

This code is free to use in any php application you like. If you like please leave me any comments, i really appreciate it.

Comments

  1. krwck says:

    should be if ($Min>$Max), not if ($min>$Max)…

Give me your feedback

This site uses Akismet to reduce spam. Learn how your comment data is processed.