Languages
[Edit]
EN

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

12 points
Created by:
Kate_C
2857

In JavaScript it is possible to randomize integer number in range with inclusive max value in following way.

1. Custom random method examples

// ONLINE-RUNNER:browser;

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

// 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
Hey ūüĎč
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.