get random number between two numbers

How to Get Random Number Between Two Numbers in JavaScript

JavaScript allows you to perform many fun and useful things with all sorts of data, including numbers. Sometimes you may need to get a random number between two numbers in JavaScript. In this article, we will learn how to do this.


How to Get Random Number Between Two Numbers in JavaScript

For most things in JavaScript that require a random number, you need to use Math.random() function. Of course, there are many third party libraries for this purpose but Math.random() will get the job done in most cases. It simply returns a random number between 0 and 1 excluding 1. We use this to do some more calculation and get our random number.

Let us say you want a random number between two numbers num1 and num2.

var num1 = 100;
var num2 = 200;

We use Match.random() function to obtain a random difference number (or delta) that you want to add to the smaller of two numbers above. You can do so with the following expression.

Math.random() * (num2 - num1 + 1) + num1

In the above example, we multiple the output of Math.random(), that is a random number between 0 and 1 (excluding 1), to the difference between our two numbers plus 1. This gives a random difference that you can add to the smaller of the two numbers, num1, to obtain random number between two numbers.

Here is an example, assuming Math.random() returns 0.51

0.51 * (200 - 100 + 1) + 100
=51.51 + 100
=151.51

Since the above result contains fractional part, we use Math.floor() function on this to convert it into an integer.

Math.floor(Math.random() * (num2 - num1 + 1) + num1)

Now the calculation becomes

Math.floor(0.51 * (200 - 100 + 1) + 100)
=Math.floor(51.51 + 100)
=Math.floor(151.51)
=151

You can include this expression in a function to make it easy to recall.

function get_random(min, max) { // min and max included 
  return Math.floor(Math.random() * (max - min + 1) + min)
}

console.log(get_random(100,200))//output 151.51

Please note, every time you run the above expression or function, you will most likely get a different output.

In this article, we have learnt how to get random number between two numbers.

Also read:

NGINX Catch All Location
How to Download Images in Python
How to Remove Trailing Newline in Python
How to Pad String in Python
How to Get Size of Object in Python

Leave a Reply

Your email address will not be published. Required fields are marked *