Possible Duplicate:
Generating random numbers in Javascript in a specific range?
Can some one tell me how to get one digit random number(1,2,3,.. not 0.1,0.2,.. or 1.0,5.0,..) using Math.random() or some other way in javascript?
Javascript creates pseudo-random numbers with the function Math. random() . This function takes no parameters and creates a random decimal number between 0 and 1. The returned value may be 0, but it will never be 1.
For example, to generate a random number between 1 and 10, we can do it like below. ThreadLocalRandom random = ThreadLocalRandom. current(); int rand = random. nextInt(1, 11);
Math. floor(Math. random() * 10) + 1 //the + 1 makes it so its not 0.
JavaScript's math.rand() is not cryptographically secure, meaning that this should NOT be used for password, PIN-code and/or gambling related random number generation. If this is your use case, please use the web crypto API instead! (w3c)
If the digit 0 is not included (1-9):
function randInt() {
return Math.floor((Math.random()*9)+1);
}
If the digit 0 is included (0-9):
function randIntWithZero() {
return Math.floor((Math.random()*10));
}
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