Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Javascript get random number in a specific range
/**
* Get a random floating point number between `min` and `max`.
*
* @param {number} min - min number
* @param {number} max - max number
* @return {float} a random floating point number
*/
function getRandom(min, max) {
return Math.random() * (max - min) + min;
}
/**
* Get a random integer between `min` and `max`.
*
* @param {number} min - min number
* @param {number} max - max number
* @return {int} a random integer
*/
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}

Thanks for this - it came in useful and helped me solve a problem today. 😀

Owner

kerimdzhanov commented Jun 2, 2015

Always welcome! Glad to know that it's helpful. :)

Thanks, it's just I need

Verten commented Jan 28, 2016

Thanks!

Very Helpful

Is the range inclusive on both ends? If I call getRandomInt(1, 5) are 1 and 5 BOTH possible returns?

@kerimdzhanov, but if the random be 1, this will not be wrong... = (

getRandomInt( 1,5 );
Math.floor(Math.random() * ( 5 - 1 + 1) + 1);
Math.floor(Math.random() * ( 5 ) + 1);
Math.floor( 1 * ( 5 ) + 1);
6;

My suggestion is limit the max. What do you think?

function getRandomInt(min, max) { return Math.min( max, Math.floor(Math.random() * (max - min + 1) + min) ); }

return (Math.random() * (max - min + 1) + min) | 0; would be faster if you are sensitive with code performance.

but now, in new chrome, there are no difference.

@AndrePessoa
Math.random() never gives 1, so there's no need to use Math.min() or @gonejack solution.

What I cannot seem to compute in my head is the "+min" at the end. I understand (max - min + 1) for inclusivity of the full range, but am at a lost to why you need the +min. What am I not getting?

function getRandomIntInclusive(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;

@hackyourcraft without "+min" the range would start at 0.

Thanks soo much!

You are best :)

When the parameter is only one. The "min" becomes the max and "min" is 0

random(min, max) {
    return (Math.random() * ((max ? max : min) - (max ? min : 0) + 1) + (max ? min : 0)) | 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment