DexieTheSheep
DexieTheSheep

Reputation: 450

JS - How can I generate a long random number?

I know that I need to use Math.random() for making random numbers, but today I tried to make a random number between 1 and 9999...(9 repeated 19 times) and my output always ends in 3-5 zeroes. How can I generate more detailed random numbers?

What I've done:

const foo = Math.floor(Math.random() * parseInt("9".repeat(19)));

Also, I'm pretty sure I know how to do this, but if anyone can tell me, how do I pad zeroes to get to a certain digit count? (ex. pad(15,4) becomes 0015 because the you need 2 more digits to make it 4 digits long)

Upvotes: 2

Views: 4642

Answers (3)

Charles Goodwin
Charles Goodwin

Reputation: 624

You need to use numbers encoded as strings. A loop like this:

var desiredMaxLength = 19
var randomNumber = '';
for (var i = 0; i < desiredMaxLength; i++) {
    randomNumber += Math.floor(Math.random() * 10);
}

Arthimetic for numbers represented as strings can be donw with the strint library found at https://github.com/rauschma/strint.

Upvotes: 2

drussey
drussey

Reputation: 713

The best idea is probably to just use a string of random integers (solves padding too):

let foo = '';
for(i=0; i<19; ++i) foo += Math.floor(Math.random() * 10);
alert(foo);

Upvotes: 3

fiddels
fiddels

Reputation: 84

You are running into Number.MAX_SAFE_INTEGER. The largest exact integral value is 2^53-1, or 9007199254740991.

Upvotes: 2

Related Questions