Get Random Number in JavaScript


The Java random number result is between 0 to 1. If you would like to select a random number within a range, you will have to do some calculations.

To get a random non-integer number within a range:
(Random_Number * (End_Of_Range - Start_Of_Range)) + Start_Of_Range

To get a random Integer number within a range, round the result value from the formula above.

e.g.

Draw a random number between 8 to 15.
Range = 8 - 15
Then the formula will be: (Random_number * (15-8))+8 = (random_number*7)+8
If the random_number is 0.3, then the result is
(0.3 * 7) + 8
= 2.1 + 8
=10.1
If the random_number is 0.9, then the result is
(0.9 * 7) + 8
= 6.3 + 8
=14.3

To store the raw random number in variable ran_num in Java Script:

var ran_num=Math.random();

Then you can use the value in variable ran_num with the above formula to get the result.

Below is an example of an integer result of range 0 to 26.
The formula is: RAW_Random_Number*(26-0)+0 = RAW_Random_Number*26

Raw Random Number: 0.503850818033119
Before rounding = 13.100121268861095
Rounded Random Number = 13

Note: Refresh the page to get another random selection.