Possible Duplicate:
Generating random whole numbers in JavaScript in a specific range
How can I get one-digit random numbers (1, 2, 3, ..., not 0.1, 0.2, ... or 1.0, 5.0, ...) using Math.random() or some other way in JavaScript?
Possible Duplicate:
Generating random whole numbers in JavaScript in a specific range
How can I get one-digit random numbers (1, 2, 3, ..., not 0.1, 0.2, ... or 1.0, 5.0, ...) using Math.random() or some other way in JavaScript?
Math.random()
returns a float between 0
and 1
, so just multiply it by 10
and turn it into an integer:
Math.floor(Math.random() * 10)
Or something a little shorter:
~~(Math.random() * 10)
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));
}
var randomnumber=Math.floor(Math.random()*10)
where 10 dictates that the random number will fall between 0-9.
Use this:
Math.floor((Math.random()*9)+1);
Math.floor((Math.random()*10));
And there goes your random integer between 0 and 10!