To generate a random number between two numbers, we can use the Math.random()
function in combination with the Math.floor()
function.
The Math.random()
function generates a random floating-point number between 0(inclusive) and 1. Whereas, the Math.floor()
function rounds down the given number to its nearest integer. We can use these two functions in combination to generate a random number in a given range.
The following example generates a random number between 10(inclusive) and 50(inclusive):
const min = 10; const max = 50; // Generate random number let random = Math.floor(Math.random()*(max - min + 1) + min); console.log(random); // Output: 34
How does it work?
As I previously said, the Math.random()
function generates a random floating-point number between 0(inclusive) and 1.
console.log(Math.random()); // 0.41 console.log(Math.random()); // 0.90 console.log(Math.random()); // 0.30 console.log(Math.random()); // 0.16
But, we don’t want the random number to be generated between 0 and 1, instead, we want to generate it in a given range.
In our case, we want the random number between 10(min) & 50(max). Therefore, we have to multiply the number generated by the Math.random()
function with (max – min + 1).
This will generate a random number between 0 and (max – min + 1) i.e. 0 and (50 – 10 + 1) = 41(not inclusive):
console.log(Math.random()*(max-min+1)); // 1.19 console.log(Math.random()*(max-min+1)); // 27.88 console.log(Math.random()*(max-min+1)); // 37.31
As we also want to set a minimum limit to the number, therefore, we have to add the min range to it. This will result in a floating-point number between min and max limit. We have set it to 10 & 50.
const min = 10; const max = 50; // Generates a floating-point number between 10 & 50 console.log(Math.random()*(max-min+1) + min); // 10.17 console.log(Math.random()*(max-min+1) + min); // 23.49 console.log(Math.random()*(max-min+1) + min); // 48.91
At last, we have to round down these floating-point numbers to their nearest integers. Therefore, we have used the Math.floor()
function.
console.log(Math.floor(15.98)); // 15 console.log(Math.floor(15.51)); // 15 console.log(Math.floor(15.00)); // 15
Thanks for reading.