How to generate random float number in PHP

2 Answers

0 votes
function randomFloat($min = 0, $max = 1) {
    return $min + mt_rand() / mt_getrandmax() * ($max - $min);
}
 
echo randomFloat() . "\n";
echo randomFloat(3, 7) . "\n";
 
 
 
/*
run: 
 
0.062633158202578
5.1917215912564
 
*/

 



answered Jul 6, 2016 by avibootz
edited Apr 14, 2024 by avibootz
0 votes
function rand_float($min, $max, $decimals = 0) {
    $dec = pow(10, $decimals);
    
    return mt_rand($min * $dec, $max * $dec) / $dec;
}
 
for ($i = 0; $i < 10; $i++) {
    echo rand_float(0, 5, 2) . "\n";
}
 
 
 
 
/*
run:
 
4.64
1.61
2.15
3.14
1.63
4.27
3.75
3.76
2.93
0.4
 
*/

 



answered Apr 14, 2024 by avibootz

Related questions

1 answer 195 views
1 answer 355 views
1 answer 161 views
1 answer 87 views
1 answer 138 views
138 views asked Sep 30, 2021 by avibootz
...