Javascript: Get random number in range.

Javascript: Get random number in range

If you want to generate a random number in a specific range in JavaScript, you can use the built-in Math.random() function. However, this function only generates a random number between 0 and 1. To generate a random number in a specific range, you need to use some additional math.

Method 1: Using Math.floor() and Math.random()

The first method to generate a random number in a range is to use the Math.floor() function along with Math.random(). The Math.floor() function rounds down a decimal number to the nearest integer. Here is the code:


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

// Usage:
console.log(getRandomNumber(1, 10)); // Returns a random number between 1 and 10

The getRandomNumber() function takes two parameters: min and max, which represent the minimum and maximum values of the range you want to generate a random number for. The function uses the formula Math.floor(Math.random() * (max - min + 1)) + min to generate a random number between min and max.

Method 2: Using Math.round() and Math.random()

The second method to generate a random number in a range is to use the Math.round() function along with Math.random(). The Math.round() function rounds a decimal number to the nearest integer. Here is the code:


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

// Usage:
console.log(getRandomNumber(1, 10)); // Returns a random number between 1 and 10

The getRandomNumber() function takes two parameters: min and max, which represent the minimum and maximum values of the range you want to generate a random number for. The function uses the formula Math.round(Math.random() * (max - min)) + min to generate a random number between min and max.

Method 3: Using parseInt() and Math.random()

The third method to generate a random number in a range is to use the parseInt() function along with Math.random(). The parseInt() function converts a string to an integer. Here is the code:


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

// Usage:
console.log(getRandomNumber(1, 10)); // Returns a random number between 1 and 10

The getRandomNumber() function takes two parameters: min and max, which represent the minimum and maximum values of the range you want to generate a random number for. The function uses the formula parseInt(Math.random() * (max - min + 1) + min) to generate a random number between min and max.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe