Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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

Example: 323760488

like image 719
AnApprentice Avatar asked Aug 09 '10 03:08

AnApprentice


People also ask

How do you generate a random number in JavaScript?

Javascript creates pseudo-random numbers with the function Math. random() . This function takes no parameters and creates a random decimal number between 0 and 1. The returned value may be 0, but it will never be 1.

How do I generate a random 6 digit number in node JS?

random() generates a random number between 0 and 1 which we convert to a string and using . toString() and take a 6 digit sample from said string using . substr() with the parameters 2, 6 to start the sample from the 2nd char and continue it for 6 characters.


1 Answers

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

like image 198
ggg Avatar answered Sep 23 '22 13:09

ggg