0 points Submitted by Shivam Arora

# How to get a random number between X(any number) and X(another number)?

We’ve been taught how to get a random number between 1 and any other number.

But what if we want to generate a random number between 2 and 10 or 5 and 10 etc.

Keeping in mind that `Math.random()` generates numbers between 0 and 1. By default, 0 would be the start value and 1 would be the end value.

So, if x = start and y = end, you would do the following:

• add x so the starting point changes from the default 0 to x
• multiply by y-x so the ending point changes from the default 1 to y
• when using `Math.floor()`, remember to +1 to y-x to accomodate the rounding downward to its nearest integer.

Formula:

``Math.floor(Math.random() * ((y-x)+1) + x);``

Example 1: a whole number between 2 and 10 would be:

``````// x = 2, y = 10
Math.floor(Math.random() * ((10-2)+1) + 2);
Math.floor(Math.random() * 9 + 2);``````

Example 2: a whole number between 5 and 10 would be:

``````// x = 5, y = 10
Math.floor(Math.random() * ((10-5)+1) + 5);
Math.floor(Math.random() * 6 + 5);``````

Example 3: a whole number between -2 and -10 would be:

``````// x = -2, y = -10
// note: no need to +1 since Math.floor() rounds down
Math.floor(Math.random() * (-10-(-2)) + (-2));
Math.floor(Math.random() * -8 - 2);``````
points almost 9 years Shivam Arora almost 9 years

Thanxx.. It helped alot. But can you please explain reason behind (y-x) more for easy understanding? Abdul almost 9 years

the (y-x) is to help in getting the number of figures withing the range. thats all.

1 vote  LiamGoodsell over 6 years