Hey Guys,

My problem is that i want to get a random number given a specific range. But it the range is a small decimal or float it rounds up. Here is what i have so far

	if(isset($xl) && isset($xu))
			$x = rand($xl,$xu);
			echo $x;

so if $xl = .065 and $xu = .095 i get a zero for $x

6 Years
Discussion Span
Last Post by diafol
$max = max(strlen(substr($xl,strpos($xl,'.')+1)),strlen(substr($xu,strpos($xu,'.')+1)));

$div = pow(10,$max); 

$xl = $xl*$div; 
$xu = $xu*$div;
if(isset($xl) && isset($xu)){
   $x = mt_rand($xl,$xu)/$div;
   echo number_format($x,$max);

You can try that, however, it won't give the right precision if the last numbers in both values is 0, e.g. 0.060 and 0.190 will give a value with 2 decimal places, not 3. Anyway, it's an ugly solution, I bet other people can think of a better way.


that worked fine for smaller numbers but when i used ranges like 12,500,000 - 17,500,000 and 2,000,000 - 3,000,000 i got negative values and small ones like so:
103.0369518 124.257917

I'm currently trying to write a function that does both small decimals and large integers...struggle.


You may hit the integer limit for mt_rand() with very large numbers.

You can check it on your version:

echo('RAND_MAX: '.mt_getrandmax());

I assume it's around 2147483647. I'm afraid I don't know of a workaround. I've seen stuff on BC_MATH, but I've never used it.

Anyway, I had a look at my code, and it didn't work for numbers with no decimals anyway, so I revamped it:

$xl= 3456189;
$max_xl = (strpos($xl,'.')===false) ? 0 : strlen(substr($xl,strpos($xl,'.')+1));
$max_xu = (strpos($xu,'.')===false) ? 0 : strlen(substr($xu,strpos($xu,'.')+1));
$max = max($max_xl,$max_xu);
$div = pow(10,$max); 
$xl = $xl*$div; 
$xu = $xu*$div;
if(isset($xl) && isset($xu)){
	$x = ($xu > $xl) ? mt_rand($xl,$xu)/$div : mt_rand($xu,$xl)/$div;
    echo number_format($x,$max);

Edited by diafol: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.