Search code examples
javascript

How do I generate a Random Number that is 9 digits in length in JavaScript


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

Example: 323760488


Solution

  • You could generate 9 random digits and concatenate them all together.

    Or, you could call random() and multiply the result by 1000000000:

    Math.floor(Math.random() * 1000000000);
    

    Since Math.random() generates a random double precision number between 0 and 1, you will have enough digits of precision to still have randomness in your least significant place.

    If you want to ensure that your number starts with a nonzero digit, try:

    Math.floor(100000000 + Math.random() * 900000000);
    

    Or pad with zeros:

    function LeftPadWithZeros(number, length)
    {
        var str = '' + number;
        while (str.length < length) {
            str = '0' + str;
        }
    
        return str;
    }
    

    Or pad using this inline 'trick'.