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

``````\$xl=\$row['x_lower'];
\$xu=\$row['x_upper'];

if(isset(\$xl) && isset(\$xu))
{
\$x = rand(\$xl,\$xu);
echo \$x;
}``````

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

## All 3 Replies

``````\$xl=0.067;
\$xu=0.194;

\$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;
\$xu=3467;

\$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);
}``````
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.