skywind
skywind

Reputation: 964

Random number with fixed length

I want to generate a random integer number with 0-9 numbers and with length = 5. I try this:

function genRand(min,max) {
    for (var i = 1; i <= 5; i++) {
        var range = max - min + 1;
        return Math.floor(Math.random()*range) + min;
    }
}

and call:

genRand(0,9);

But it always returns 1 number, not 5 (

Help please!

Upvotes: 5

Views: 18571

Answers (5)

Jacob
Jacob

Reputation: 595

Here's a more generalized version of Nate B's answer:

function rand(digits) {
    return Math.floor(Math.random()*parseInt('8' + '9'.repeat(digits-1))+parseInt('1' + '0'.repeat(digits-1)));
}

Upvotes: 2

kennebec
kennebec

Reputation: 104770

The smallest 5 digit number is 10000, the largest is 99999, or 10000+89999.

Return a random number between 0 and 89999, and add it to the minimum.

var ran5=10000+Math.round(Math.floor()*90000)

Math.floor rounds down, and Math.random is greater than or equal to 0 and less than 1.

Upvotes: 2

phoxis
phoxis

Reputation: 61910

To get a 5 digit random number generate random numbers between the range (10000, 99999). Or generate randomly 5 single digits and paste them.

EDIT

The process you have shown simply will generate one number and return to the caller. The think which might work is (pseudo code) :

int sum = 0;
int m = 1;
for (i=0;i<5;i++)
{
  sum = sum  + m * random (0, 9);
  /*       or                  */
  sum = sum * m + random (0, 9);
  m = m * 10;
}

Or better generate 5 digit random numbers with rand (10000, 99999)

Upvotes: 1

Nate B
Nate B

Reputation: 6356

   function genRand() {
      return Math.floor(Math.random()*89999+10000);
   }

Upvotes: 15

graphicdivine
graphicdivine

Reputation: 11211

return exits the function on the first loop.

Upvotes: 9

Related Questions