Random number generator for JavaScript

July 7, 2009 – 8:42 pm

Need to know how to generate a random number in JavaScript? The following code will do the job. There are a lot of articles on the internet explaining how to generate a random number between 0 and 10 (for example), but not so many explaining how to generate a random number within a certain specified range. And of those solutions, some of these didn’t produce very random results. The solution below, I’ve tested with 10,000 repetitions and found that there was a good even distribution over all numbers in the specified range.

// 'min' and 'max' are inclusive.
function randomNumber(min, max)
{
    return Math.floor((max + 1 - min) * Math.random() + min);
}

// Example: to select a random number between 5 and 20 (inclusive).
var num = randomNumber(5,20);
Your Ad Here

Post a Comment