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
Math.random()
Generates a floating-point number between0
(inclusive) and1
(exclusive).
Example:0.456
,0.999
.- Scale to the desired range
Multiply by(max - min + 1)
to cover the full range of integers.
Example: Formin = 5
,max = 10
:Math.random() * (10 - 5 + 1) = Math.random() * 6
→0 ≤ value < 6
. - Convert to an integer
UseMath.floor()
to round down to the nearest integer.
Example:5.999
→5
. - Shift to the
min
value
Addmin
to shift the result into the desired range.
Example:5 + 5 = 10
(max is inclusive).
Examples
Use Case | Code | Output Range |
---|---|---|
Integer between 1–10 | getRandomInt(1, 10) | 1, 2, ..., 10 |
Integer between 5–20 | getRandomInt(5, 20) | 5, 6, ..., 20 |
Simulate a dice roll | getRandomInt(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 bothmin
andmax
.getRandomFloat
includesmin
but excludesmax
.- Edge Cases:
- If
min
>max
, swap them:javascript if (min > max) [min, max] = [max, min];
- If
min === max
, returnmin
.
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!