Skip to content
Advertisement

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

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

Example: 323760488

Advertisement

Answer

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’.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement