Skip to content
the poor coder

math.random between two numbers

Poor Man
Published
Reading time
1 min read
On this page

Generating a random number between two numbers using Math.random() in JavaScript#

If you want to generate a random number between two specified numbers, you can use the Math.random() method in JavaScript. This method returns a random number between 0 (inclusive) and 1 (exclusive).

Here is an example:

Text

function getRandomNumber(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

var randomNumber = getRandomNumber(1, 10);
console.log(randomNumber); // prints a random integer between 1 and 10 (inclusive)

Explanation#

In the getRandomNumber function, we first calculate the difference between the two numbers (max - min + 1) and multiply it with the result of Math.random(). This gives us a random number between 0 and the difference.

We then add the minimum value to this number to shift it within the desired range. Finally, we use Math.floor() to round down to the nearest integer.

The result is a random integer between the minimum and maximum values (inclusive).

Alternative Approach#

You can also use the following approach:

Text

var randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;

This approach calculates a random number between 0 and the difference, adds it to the minimum value, and rounds down to the nearest integer in one step.

Both approaches are valid and will give you a random number between the specified range.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC