Menu
JavaScript to Generate a Random Number Between X and Y

You can use the JavaScript Math object's .random() method to generate a random number between two values, but because it returns a (pseudo) random floating-point number between 0 and 1 (but not including 1), you'll need to perform some additional operations on it to scale it to your required range.

To generate a random integer between two values x and y use the code shown below:

Math.floor((Math.random() * y) + x);

x being the lowest value, and y being the highest value.

For example if you wanted to generate a random integer between 1 and 8, you would use:

Math.floor((Math.random() * 8) + 1);

The Math.floor() function returns the largest integer less than or equal to the passed argument.

If the lowest random integer that you require is 0, you can simplify the statement as shown below:

Math.floor(Math.random() * max);

To generate a random floating-point number between two values x and y you would use the code shown below:

return Math.random() * (max-min) + min;


Learn more at amazon.com

More Java Script Code:
• Four Ways to Use Java Script Event Handlers
• Regular Expression Basics : Match a Set of Characters
• Web Site Menus : Which Section Am I In?
• JavaScript to Add and Remove Rows and Cells from a Table
• Code for Java Script Cube / Box Volume Calculator
• Calculators for Your Website : Decimal to Hexidecimal Converter
• JavaScript Code for Binary to Hexadecimal - Hexadecimal to Binary Conversion
• Convert Mixed Number to Decimal
• Java Script Math Object Trigonometric Methods
• A Cross-Browser Solution for Handling JavaScript Events