Random number with fixed length

2019-04-10 16:03发布

问题:

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!

回答1:

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


回答2:

return exits the function on the first loop.



回答3:

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.



回答4:

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)



回答5:

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)));
}