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.
1. Custom random method examples
// ONLINE-RUNNER:browser;
/*
inclusive min (result can be equal to min value)
exclusive max (result will not be to max value)
*/
function randomizeInteger(min, max) {
if(max == null) {
max = (min == null ? Number.MAX_SAFE_INTEGER : min);
min = 0;
}
min = Math.ceil(min); // inclusive min
max = Math.floor(max); // exclusive max
if(min > max - 1) {
throw new Error("Incorrect arguments.");
}
return min + Math.floor((max - min) * Math.random());
}
// Example:
console.log(randomizeInteger()); // 5547382624322139
console.log(randomizeInteger(5)); // 3
console.log(randomizeInteger(10, 80)); // 62
console.log(randomizeInteger(-50, 50)); // -8