Generate random number between two numbers in JavaScript
javascript, random
Solution
Important
The following code works only if the minimum value is `1`. It does not work for minimum values other than `1`.
If you wanted to get a random integer between 1 (and only 1) and 6, you would calculate:
const rndInt = Math.floor(Math.random() * 6) + 1
console.log(rndInt)
Where:
- 1 is the start number
- 6 is the number of possible results (1 + start (6) - end (1))
Problem
Is there a way to generate a random number in a specified range with JavaScript ? For example: a specified range from 1 to 6 were the random number could be either 1, 2, 3, 4, 5, or 6.
Related problems
- Generating random whole numbers in JavaScript in a specific range
- What does this square bracket and parenthesis bracket notation mean [first1,last1)?
- What is the "double tilde" (~~) operator in JavaScript?
- Using bitwise OR 0 to floor a number
- What is JavaScript's highest integer value that a number can go to without losing precision?