Alexey Berezuev
Alexey Berezuev

Reputation: 793

PHP How do I rand float value?

$a = floatval(0.0001);
$b = floatval(0.0009);
$c = rand($a,$b); // int(0);

How can I get rand from $a to $b floats?
Multiplication of $a and $b is not solution, because I don't know number of digits after dot.

Upvotes: 0

Views: 694

Answers (3)

roberto06
roberto06

Reputation: 3864

Yet another solution is to count the number of decimals and do a rand on the numbers powered by this number :

function count_decimals($x) {
   return strlen(substr(strrchr($x+"", "."), 1));
}

function random($min, $max, $precision = 0) {
   $decimals = max(count_decimals($min), count_decimals($max)) + $precision;
   $factor = pow(10, $decimals);
   return rand($min*$factor, $max*$factor) / $factor;
}

var_dump(random(0.001, 0.009)); // 0.004
var_dump(random(0.001, 0.009, 1)); // 0.0046
var_dump(random(0.001, 0.009, 2)); // 0.00458
var_dump(random(0.001, 0.009, 5)); // 0.00458014

I added the $precision parameter so you can choose how many more decimals you want to append in your random number.

Upvotes: 0

N. Hamelink
N. Hamelink

Reputation: 603

You are able to create the random with values above 0, and devide it.

$a = 1;
$b = 9;
$c = rand($a, $b);
$c = $c / 10000;

Upvotes: 0

A.Mikhailov
A.Mikhailov

Reputation: 466

From this article:

An elegant way to return random float between two numbers:

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

Upvotes: 2

Related Questions