post your comment   print   send to a friend
Rate:   0% | Views: 490
Question categories:  JavaScript

Generating a random number in JavaScript

 

A random number is useful in the creation of certain popular JavaScript applications, such as dice, random image script, or random link generator. Here, we will learn how to output a random number that falls within the range 1 to x, where x is any integer >1. The results may be unpredictable, but the technique is not. To generate a random number in JavaScript, simply use the following code:

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

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

Why Math.floor(), instead of Math.round(), is used in the above code
While both expressions successfully round off containing parameters to an integer within the designated range, Math.floor does this more "evenly." The resulting integer is not skewed toward either end of the number spectrum. In other words, a more random number is returned using Math.floor().

 

Customer Feedback
Rate:   0% | Views: 490 | Please Rate:  
 
If you have other comments or ideas for future technical tips, please type them here:

Email: (optional)

Comments: (optional)

 Cheap Web Hosting | Hosting Service    Back to serch results
Browse the Base
Knowledge Base
Web Design
  Do It Yourself
    JavaScript
Messages
Private Area
 
Ask
in Private
   
Personal
Folder
 
Related Questions
 
1. Calculating days remaining until Christmas
 
2. Detecting browser type
 
3. Determining browser type using object detection
 
4. The Internet Explorer challenge
 
5. JavaScript and Forms
 
Home Browse Search Ask in Private Personal Folder   Help
powered by web hosting 
  Logged as: Guest