EN
JavaScript - random integer number in range with exclusive max value example
9 points
In this article, we would like to show you how to randomize integer numbers in a range with an exclusive max value in JavaScript.
xxxxxxxxxx
1
/*
2
inclusive min (result can be equal to min value)
3
exclusive max (result will not be 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
11
min = Math.ceil(min); // inclusive min
12
max = Math.floor(max); // exclusive max
13
14
if(min > max - 1) {
15
throw new Error("Incorrect arguments.");
16
}
17
18
return min + Math.floor((max - min) * Math.random());
19
}
20
21
// Example:
22
23
console.log(randomizeInteger()); // 5547382624322139
24
console.log(randomizeInteger(5)); // 3
25
console.log(randomizeInteger(10, 80)); // 62
26
console.log(randomizeInteger(-50, 50)); // -8