Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use PHP To Generate Random Decimal Beteween Two Decimals

Tags:

php

random

I need to generate a random number, to the 10th spot between 2 decimals in PHP.

Ex. A rand number between 1.2 and 5.7. It would return 3.4

How can I do this?

like image 331
Nick Roskam Avatar asked May 02 '12 18:05

Nick Roskam


3 Answers

You can use:

rand ($min*10, $max*10) / 10 

or even better:

mt_rand ($min*10, $max*10) / 10 
like image 92
codaddict Avatar answered Sep 23 '22 13:09

codaddict


You could do something like:

rand(12, 57) / 10

PHP's random function allows you to only use integer limits, but you can then divide the resulting random number by 10.

like image 38
Deleteman Avatar answered Sep 23 '22 13:09

Deleteman


A more general solution would be:

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

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

$answer = random(1.2, 5.7);
like image 40
driangle Avatar answered Sep 25 '22 13:09

driangle