EN
JavaScript - random integer number in range with inclusive max value example
15 points
In this article, we would like to show you how to randomize integer numbers in a range with an inclusive max value in JavaScript.
xxxxxxxxxx
1
/*
2
inclusive min (result can be equal to min value)
3
inclusive max (result can be equal to max value)
4
*/
5
function randomizeInteger(min, max) {
6
if(max == null) {
7
max = (min == null ? Number.MAX_SAFE_INTEGER : min);
8
min = 0;
9
}
10
min = Math.ceil(min); // inclusive min
11
max = Math.floor(max); // exclusive max
12
if(min > max - 1) {
13
throw new Error("Incorrect arguments.");
14
}
15
return min + Math.floor((max - min + 1) * Math.random());
16
}
17
18
19
// Usage example:
20
21
console.log(randomizeInteger()); // 5918572174489812
22
console.log(randomizeInteger(5)); // 5
23
console.log(randomizeInteger(10, 80)); // 60
24
console.log(randomizeInteger(-50, 50)); // -15