Benedict Lewis
Benedict Lewis

Reputation: 2813

Generating a random four digit pin, last digit is always zero

I'm trying to generate a four digit pin code, between 0000 and 9999 using Javascript. I've had the problem that naturally, numbers like 403 will be generated, so everything is prefixed with 0 and then I use substr to get the last four digits.

For some reason, the last number is always zero, and I have no idea why:

function generatePin () {
    min = 0,
    max = 9999;
    return ("0" + Math.floor(Math.random() * (max - min + 1)) + min).substr(-4);
}

The output from running it 10 times is:

2200
1070
9370
4870
5190
5490
5240
7410
1190
0220
2310

Upvotes: 4

Views: 4935

Answers (3)

Ori Folger
Ori Folger

Reputation: 1086

Math.random().toString().substr(2,4)

Upvotes: 5

Janak
Janak

Reputation: 5052

You can use pair of brackets to surpass this.

function generatePin () {
    min = 0,
    max = 9999;
    return ("0" + (Math.floor(Math.random() * (max - min + 1)) + min)).substr(-4);
}

" + min " was causing the trailing zero to append.

Upvotes: 2

Sam Hanley
Sam Hanley

Reputation: 4755

It's ending with a 0 because at the end of your number you have + min, and min is 0. It's performing string concatenation, not integer addition, so you're tacking on a zero to the end. Just remove that bit and it will fix the issue.

And Buck Doyle (pardon the fact that I don't know how to link to a user) is quite right -- if you're going to parse the whole thing as a string, you'll need some more leading zeroes. Three zeroes out front will give you a four-digit string even if you randomized a 1.

Upvotes: 5

Related Questions