tags:

views:

88

answers:

5

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

Example: 323760488

+3  A: 

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

ggg
AnApprentice
How would that be 9 digits in length? 9 digits needs to be a fixed length never more or less
AnApprentice
just need to handle cases like 0.000001234, pad with zeros up to 9 digits
Mitch Wheat
@nobosh: 0 is a valid digit, even on the left side of your number. If you wanted a number >= 100000000, then you would have to say so (I've updated my answer to cover this case).
ggg
convert the resulting number to a string. Pad with zeroes on left if length < 9. Zeroes are perfectly good random numbers and should not suffer discrimination!
Larry K
@nobosh: It depends, are leading zeros allowed? For example, is `000000001` a valid number?
slebetman
A: 

Math.floor(Math.random()*899999999 + 100000000);

hythlodayr
has a bias.....
Mitch Wheat
A: 

Start with the smallest 10-digit number, then subtract off a random number less than 1,000,000,000. Like so:

1000000000 - Math.floor(Math.random() * 1000000000);
Zach Rattner
A: 

Screen scrape this page:

JohnB
A: 

why don't just extract digits from the Math.random() string representation?

Math.random().toString().slice(2,11);
/*
Math.random()                         ->  0.12345678901234
             .toString()              -> "0.12345678901234"
                        .slice(2,11)  ->   "123456789"
 */

(requirement is that every javascript implementation Math.random()'s precision is at least 9 decimal places)

mykhal