Generate a random number in given range using JavaScript
Today we’ll show you how to generate a random number in given range using JavaScript. In the previous article we have explained about Generating an n-digit random number.
- Load script dynamically and add the callback in JavaScript
- List of do’s and don’ts in JavaScript for best practices
- Sorting an array in JavaScript
- How to detect the user browser in JavaScript
- Difference between var, let and const in JavaScript
- Get a random number between two numbers including min and max numbers
- Get a random number between 0 to n number
1. Get a random number between two numbers including min and max numbers
By the use of the below method, you will get the random number between two numbers including min and max values.
// get random number including min and max
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
getRandomNumber(0, 50); // Output: 43
We have used the Math.random()
method to generate the random values and Math.floor
method to round a number downward to its nearest integer. You have to pass the min and max values in the parameter of the function to generate a random number between those values.
2. Get a random number between 0 to n number
Use the below method to get a random number between 0 to n number.
// get random number by passing max number
function getRandomNumber(max) {
return Math.floor(Math.random() * max);
}
getRandomNumber(50); // Output: 47
In the above method, we have used the single parameter as max value and based on it we are generating the random number between 0 to max value. We have used the same methods Math.random()
and Math.floor()
to generate the random number.
I hope you find this article helpful.
Thank you for reading. Happy Coding..!!