Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to return a random number between 1 and 200 with JavaScript?
To return a random number between 1 and 200, use JavaScript's Math.random() and Math.floor() methods.
How It Works
Math.random() generates a decimal between 0 (inclusive) and 1 (exclusive). To get integers from 1 to 200:
- Multiply by 200 to get 0 to 199.999...
- Use
Math.floor()to round down to 0-199 - Add 1 to shift the range to 1-200
Example
You can try to run the following code to return a random number in JavaScript.
<!DOCTYPE html>
<html>
<body>
<script>
document.write(Math.floor(Math.random() * 200) + 1);
</script>
</body>
</html>
Alternative Approach with Function
function randomBetween(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Generate random number between 1 and 200
console.log(randomBetween(1, 200));
console.log(randomBetween(1, 200));
console.log(randomBetween(1, 200));
156 42 189
Step-by-Step Breakdown
let randomDecimal = Math.random();
console.log("Random decimal:", randomDecimal);
let scaled = randomDecimal * 200;
console.log("Scaled (0-199.999):", scaled);
let floored = Math.floor(scaled);
console.log("Floored (0-199):", floored);
let final = floored + 1;
console.log("Final result (1-200):", final);
Random decimal: 0.7834592841 Scaled (0-199.999): 156.69185682 Floored (0-199): 156 Final result (1-200): 157
Conclusion
Use Math.floor(Math.random() * 200) + 1 to generate random integers from 1 to 200. The formula ensures uniform distribution across the entire range.
Advertisements
