W3docs

How to Generate a Random Number Between Two Numbers in JavaScript

It is frequently necessary to generate a random number between two numbers while working with JavaScript. This snippet will help you to do it efficiently.

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 <kbd class="highlighted">Math.random()</kbd> method, you can generate random float (number with decimals) between <kbd class="highlighted">0</kbd> and <kbd class="highlighted">1</kbd>.

Javascript math random method

javascript— editable

If you want to get an integer instead of a float, you should apply the <kbd class="highlighted">Math.floor()</kbd> in combination with <kbd class="highlighted">Math.random()</kbd>.

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

javascript— editable

In this example, 1 is the minimum value, and 5 is the maximum value. The formula for an inclusive range is <kbd class="highlighted">(max - min + 1)</kbd>.

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

<kbd class="highlighted">Math.random()</kbd> is used for returning 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.

<kbd class="highlighted">Math.floor()</kbd> 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.