I'm looking for a way to generate a random number that is divisible by 10, such as 10
, 20
, 30
, 40
, 50
and so on…
How could I acplish this in JavaScript?
I'm looking for a way to generate a random number that is divisible by 10, such as 10
, 20
, 30
, 40
, 50
and so on…
How could I acplish this in JavaScript?
Share Improve this question edited Feb 25, 2014 at 6:37 Golo Roden 151k102 gold badges314 silver badges442 bronze badges asked Feb 24, 2014 at 18:55 iargueiargue 692 silver badges13 bronze badges 1- 2 Base 10 is pretty mon. I am sure that's not what you mean by 10, 20, 30, 40, 50. – user2591612 Commented Feb 24, 2014 at 18:58
1 Answer
Reset to default 11Calculate an integer random number between 1 and 5, and multiply it by 10.
There are lots of tutorials out there on how to acplish the first task. E.g., use
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
(Taken from Math.random() documentation on MDN.)
And, as said, multiply the result by 10 … that's it.
So, a plete example might be:
function getRandom10() {
return getRandomInt(1, 5) * 10; // Returns 10, 20, 30, 40 or 50
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
If you need to configure this, use:
function getRandom10(min, max) {
return getRandomInt(min / 10, max / 10) * 10;
}
And call it like:
getRandom10(30, 70); // => 30, 40, 50, 60 , 70