I’m looking for an efficient, elegant way to generate a JavaScript variable that is 9 digits in length:
Example: 323760488
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You could generate 9 random digits and concatenate them all together.
Or, you could call
random()and multiply the result by 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:
Or pad with zeros:
Or pad using this
inline ‘trick’.