How to generate random float in specific range with PHP

1 Answer

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 < 20; $i++) {
    echo rand_float(2, 7, 3) . "\n";
}




/*
run:

5.246
3.79
4.208
2.39
3.947
5.749
3.607
5.481
2.751
6.632
5.682
3.058
5.408
6.14
6.39
3.877
3.674
2.806
3.714
3.045

*/

 



answered Jun 2, 2022 by avibootz

Related questions

1 answer 132 views
1 answer 185 views
1 answer 141 views
1 answer 143 views
1 answer 129 views
2 answers 132 views
...