To generate a random number between 0 and X, use the below javascript:

var myRandomNumber = Math.floor(Math.random()*(X+1))

Therefore, if you want from 0 and 100, you simply need:

var myRandomNumber = Math.floor(Math.random()*101)

Now, a bit more complicated! If we want a number between the range of X and Y, follow the below formula:

var myRandomNumber = Math.floor(Math.random()*(Y-X))+X

And another real world example. Assume we want a random number from 79 and 473:

var myRandomNumber = Math.floor(Math.random()*394)+79

This entry was posted on Tuesday, May 27th, 2008 at 7:02 am and is filed under Javascript. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply