How to generate random number between two numbers in JavaScript?

To generate a random integer between two numbers (inclusive) in JavaScript, use the following formula:

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

Explanation

  1. Math.random()
    Generates a floating-point number between 0 (inclusive) and 1 (exclusive).
    Example: 0.456, 0.999.
  2. Scale to the desired range
    Multiply by (max - min + 1) to cover the full range of integers.
    Example: For min = 5, max = 10:
    Math.random() * (10 - 5 + 1) = Math.random() * 60 ≤ value < 6.
  3. Convert to an integer
    Use Math.floor() to round down to the nearest integer.
    Example: 5.9995.
  4. Shift to the min value
    Add min to shift the result into the desired range.
    Example: 5 + 5 = 10 (max is inclusive).

Examples

Use CaseCodeOutput Range
Integer between 1–10getRandomInt(1, 10)1, 2, ..., 10
Integer between 5–20getRandomInt(5, 20)5, 6, ..., 20
Simulate a dice rollgetRandomInt(1, 6)1, 2, ..., 6

For Floating-Point Numbers

To generate a floating-point number between min (inclusive) and max (exclusive):

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

Example:
getRandomFloat(1.5, 4.5) → Returns values like 1.5, 3.2, or 4.499.

Key Notes

  • Inclusive vs. Exclusive:
  • getRandomInt includes both min and max.
  • getRandomFloat includes min but excludes max.
  • Edge Cases:
  • If min > max, swap them:
    javascript if (min > max) [min, max] = [max, min];
  • If min === max, return min.

Live Demo

// Generate a random integer between 5 and 10 (inclusive)
console.log(getRandomInt(5, 10)); // Example output: 7

// Generate a random float between 2.5 and 5.5 (exclusive of 5.5)
console.log(getRandomFloat(2.5, 5.5)); // Example output: 3.789

This approach ensures you get a uniformly distributed random number within your specified range!

Leave a Reply

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