Languages
[Edit]
EN

JavaScript - random integer number in range with inclusive max value example

15 points
Created by:
Vanessa-Drake
718

In this article, we would like to show you how to randomize integer numbers in a range with an inclusive max value in JavaScript.

Practical example

// ONLINE-RUNNER:browser;

/*
	inclusive min (result can be equal to min value)
    inclusive max (result can be equal 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 + 1) * Math.random());
}


// Usage example:

console.log(randomizeInteger());         //  5918572174489812
console.log(randomizeInteger(5));        //  5
console.log(randomizeInteger(10, 80));   //  60
console.log(randomizeInteger(-50, 50));  // -15

 

See also

  1. JavaScript - Math.random() method example
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - random

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join