5

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!

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
skywind
  • 892
  • 6
  • 22
  • 44

5 Answers5

15
   function genRand() {
      return Math.floor(Math.random()*89999+10000);
   }
Nate B
  • 6,338
  • 25
  • 23
9

return exits the function on the first loop.

graphicdivine
  • 10,937
  • 7
  • 33
  • 59
2

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)));
}
Jacob
  • 527
  • 1
  • 5
  • 14
2

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.

kennebec
  • 102,654
  • 32
  • 106
  • 127
1

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)

phoxis
  • 60,131
  • 14
  • 81
  • 117
  • "generate randomly 5 single digits from 0 to 9 and paste them" YES! – skywind Dec 12 '11 at 14:57
  • 1
    isn't it better to simply generate random numbers within the range (10000, 99999) ?? For pasting the 5 randomly generated digits (0 to 9) you need to perform 5 multiplications and 5 additions. – phoxis Dec 12 '11 at 14:57