Skip to content

Instantly share code, notes, and snippets.

@LeanSeverino1022
Last active September 10, 2019 08:16
Show Gist options
  • Save LeanSeverino1022/53cb557610241ebce88753761561f892 to your computer and use it in GitHub Desktop.
Save LeanSeverino1022/53cb557610241ebce88753761561f892 to your computer and use it in GitHub Desktop.
Javascript get random number in a specific range #vanillajs
//NOTE: Math.random() returns a floating point number from 0 up to but not including 1.
//1. inclusive at the minimum, exclusive at the maximum
var max = 10;
var min = 1;
var result = Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
/** helper function version **/
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}
//example:
//Math random result is .01, then... Math.floor(.01 * (10 - 1)) + 1 = 1 //min is 1(inclusive)
// Math random result is .99, then... Math.floor(.99 * (10 - 1)) + 1 = 9 //not 10, max is exclusive
//2. inclusive at both the minimum and the maximum
var max = 10;
var min = 1;
var result = Math.floor(Math.random() * (max - min + 1)) + min; //The maximum is inclusive and the minimum is inclusive
/*helper function version*/
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; //The maximum is inclusive and the minimum is inclusive
}
//example:
//Math random result is .01, then... Math.floor(.01 * (10(max) - 1(min) + 1)) + 1(min) = 1 //min is 1(inclusive)
// Math random result is .99, then... Math.floor(.99 * (10(max) - 1(min) + 1)) + 1(min) = 10 //max is 10(inclusive)
//src: MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment