Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 688
Benedict Lewis Avatar asked Oct 24 '25 19:10

Benedict Lewis


2 Answers

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.

like image 115
Sam Hanley Avatar answered Oct 26 '25 10:10

Sam Hanley


Math.random().toString().substr(2,4)
like image 22
Ori Folger Avatar answered Oct 26 '25 09:10

Ori Folger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!