$value = rand(0.1, 0.3);
then the output returns 0
Any answers that could fix this?
I already tried to use
$value = 0.01*rand(1, 3);
still I get 0
The documentation says it all:
rand
— Generate a random integer
Because you are passing floats (0.1
and 0.3
), they are converted to int
s and the result is exactly as this:
rand(0, 0)
Proof of the conversion: http://ideone.com/osg97
On the basis of the above, the only result may be getting from rand(0.1, 0.3)
is 0
(zero). To get something else, base it on integers.
The solution is simple, just use integer for calculation. If you want function that is ready for your needs, you can use this code ($places
is number of digits you want to calculate for after integral part):
function float_rand($start, $end, $places){
$multiplier = pow(10, $places);
return rand($start * $multiplier, $end * $multiplier) / $multiplier;
}
Proof: http://ideone.com/lfUhx
$value = 0.01*rand(1, 3); var_dump($value);
--- it's not0
$value
gets used as an integer.