snippetjavascriptCritical
Generate random number between two numbers in JavaScript
Viewed 0 times
numbersrandombetweengeneratenumbertwojavascript
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.
For example: a specified range from 1 to 6 were the random number could be either 1, 2, 3, 4, 5, or 6.
Solution
Important
The following code works only if the minimum value is
If you wanted to get a random integer between 1 (and only 1) and 6, you would calculate:
Where:
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))
Context
Stack Overflow Q#4959975, score: 2535
Revisions (0)
No revisions yet.