I'm looking for an efficient, elegant way to generate a JavaScript variable that is 9 digits in length:
Example: 323760488
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.
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.
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'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With