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
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.
Math.random().toString().substr(2,4)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With