JavaScript, Generate a Random Number that is 9 numbers in length

Viewed 130628

I'm looking for an efficient, elegant way to generate a JavaScript variable that is 9 digits in length:

Example: 323760488

17 Answers
Math.random().toFixed(length).split('.')[1]

Using toFixed alows you to set the length longer than the default (seems to generate 15-16 digits after the decimal. ToFixed will let you get more digits if you need them.

function rand(len){var x='';
 for(var i=0;i<len;i++){x+=Math.floor(Math.random() * 10);}
 return x;
}

rand(9);

Does this already have enough answers?
I guess not. So, this should reliably provide a number with 9 digits, even if Math.random() decides to return something like 0.000235436:

Math.floor((Math.random() + Math.floor(Math.random()*9)+1) * Math.pow(10, 8))

I know the answer is old, but I want to share this way to generate integers or float numbers from 0 to n. Note that the position of the point (float case) is random between the boundaries. The number is an string because the limitation of the MAX_SAFE_INTEGER that is now 9007199254740991

Math.hRandom = function(positions, float = false) {

  var number = "";
  var point = -1;

  if (float) point = Math.floor(Math.random() * positions) + 1;

  for (let i = 0; i < positions; i++) {
    if (i == point) number += ".";
    number += Math.floor(Math.random() * 10);
  }

  return number;

}
//integer random number 9 numbers 
console.log(Math.hRandom(9));

//float random number from 0 to 9e1000 with 1000 numbers.
console.log(Math.hRandom(1000, true));

function randomCod(){

    let code = "";
    let chars = 'abcdefghijlmnopqrstuvxwz'; 
    let numbers = '0123456789';
    let specialCaracter = '/{}$%&@*/()!-=?<>';
    for(let i = 4; i > 1; i--){

        let random = Math.floor(Math.random() * 99999).toString();
        code += specialCaracter[random.substring(i, i-1)] + ((parseInt(random.substring(i, i-1)) % 2 == 0) ? (chars[random.substring(i, i-1)].toUpperCase()) : (chars[random.substring(i, i+1)])) + (numbers[random.substring(i, i-1)]);
    }

    code = (code.indexOf("undefined") > -1 || code.indexOf("NaN") > -1) ? randomCod() : code;


    return code;
}
  1. With max exclusive: Math.floor(Math.random() * max);

  2. With max inclusive: Math.round(Math.random() * max);

To generate a number string with length n, thanks to @nvitaterna, I came up with this:

1 + Math.floor(Math.random() * 9) + Math.random().toFixed(n - 1).split('.')[1]

It prevents first digit to be zero. It can generate string with length ~ 50 each time you call it.

var number = Math.floor(Math.random() * 900000000) + 100000000
Related