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:

JavaScript

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:

JavaScript

Or pad with zeros:

JavaScript

Or pad using this inline ‘trick’.

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