Skip to content
Create a gist now

Instantly share code, notes, and snippets.

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);
}
@neurotech

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

@kerimdzhanov
Owner

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

@alvarod-infocorp

Thanks, it's just I need

@Verten
Verten commented Jan 28, 2016

Thanks!

@cjseeger

Very Helpful

@PrincessRTFM

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

@AndrePessoa

@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) );
}

@gonejack

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.

@fernandocanizo

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

@hackyourcraft

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;

@voidvoxel

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.