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
x
2
1
Math.floor(Math.random() * 1000000000);
2
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
1
2
1
Math.floor(100000000 + Math.random() * 900000000);
2
Or pad with zeros:
JavaScript
1
10
10
1
function LeftPadWithZeros(number, length)
2
{
3
var str = '' + number;
4
while (str.length < length) {
5
str = '0' + str;
6
}
7
8
return str;
9
}
10
Or pad using this inline ‘trick’.