TomRed.net

  • Increase font size
  • Default font size
  • Decrease font size
Subscribe Bookmark and Share
Home Tutorials JavaScript JavaScript Random Number Generator

JavaScript Random Number Generator

User Rating: / 0
PoorBest 

There is always a need to generate a random number when developing.  Maybe you want to select a quote at random or your creating a chance element in a game, in either or any case this can be easily achieve.  In the example below I use Math.random().  The results may be unpredictable, but the technique to getting them certainly is not. To generate a random number in JavaScript, simply use the following code:

	var randomnumber=Math.floor(Math.random()*11)

where 11 dictates that the random number will fall between 0-10. To increase the range to, say, 100, simply change 11 to 101 instead.

Some of you may be curious as to why Math.floor(), instead of Math.round(), is used in the above code. While both successfully round off its containing parameter to an integer within the designated range, it is said that Math.floor does so more "evenly", so the resulting integer isn't lopsided towards either end of the number spectrum. In other words, a more random number is returned using Math.floor().  I think the results are pretty similar myself to demonstrate I will show you a sample I have outlined below you can see the average is the same and spread are pretty even.

 

I hope you found this useful, if you have any questions leave a comment or email support[@]tomred.net