Random numbers in JavaScript

Posted: March 25th, 2009 | Author: Henrie Media Inc. | Filed under: JavaScript | No Comments »

ComputerI am often asked the question of how to generate random numbers in JavaScript. It’s a little tricky and 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, 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().

Print, Email, Share, Enjoy!
  • Print
  • email
  • Twitter
  • Facebook
  • Digg
  • MySpace
  • Mixx
  • del.icio.us
  • Technorati
  • StumbleUpon

Leave a Reply