How to Generate a Random Number Between Two Numbers in JavaScript

In this snippet, you can find a way of generating a random number between two numbers.

Here is how to do it.

With the help of the Math.random() method, you can generate random float (number with decimals) between 0 and 1.

Javascript math random method
// Logs something like this: 0.7433471138781795 // It will be different every time var rand = Math.random(); console.log(rand);

If you want to get an integer instead of a float, you should apply the Math.floor() in combination with Math.random().

So, if you need to get a random integer between 1 and 5, you should calculate it as follows:

Javascript math floor and math random method
let math = Math.floor(Math.random() * 5) + 1; console.log(math);

In this example, 1 is considered the starting number, and 5 is the number of the possible results (1 + start (5) - end (1)).

Describing Math.random()and Math.floor()

Math.random() is used for returning return a floating-point pseudo-random number between range [0,1) , 0 (inclusive) and 1 (exclusive). It can then be scaled in line with the expected range.

Math.floor() in JavaScript is used for rounding off the number passed as a parameter to its nearest integer in downward direction of rounding (towards the lesser value). It accepts one parameter value that is number to be rounded to its nearest integer in downward rounding.