1
$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

4
  • 3
    $value = 0.01*rand(1, 3); var_dump($value); --- it's not 0
    – zerkms
    Sep 11, 2012 at 4:53
  • 1
    What does number does "getrandmax()" output?
    – Chris
    Sep 11, 2012 at 4:54
  • Sounds like you've got some other code not shown here where $value gets used as an integer.
    – Brad
    Sep 11, 2012 at 4:56
  • The first one is 0 because rand only accepts INTEGERS. The second one... is not 0. It's a float, you sure you don't cast it to an int somewhere?
    – sachleen
    Sep 11, 2012 at 4:56

2 Answers 2

3

The function rand(); only accepts integers and not float number values.

0
0

Problem

The documentation says it all:

rand — Generate a random integer

Because you are passing floats (0.1 and 0.3), they are converted to ints 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.

Solution

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.