Javascript Program to Generate a Random Number Between Two Numbers
There are times in web development when you need to generate a random number between two specified values. The need to generate a random number arises, for instance, when designing a game or quiz. Here, we'll see on how to use JavaScript to generate a random number between two specified values.
The "Math.random()" built-in JavaScript method that generates a random value between 0 and 1. (exclusive of 1).
We also have an interactive JavaScript course where you can learn JavaScript from basics to advanced and get certified. Check out the course and learn more from here.
What is Math.random() Method?
Math.random()
returns a random number between 0 (inclusive), and 1 (exclusive)
The Formula to find a random integer between min (inclusive) to max (inclusive), is as follows:
Math.floor(Math.random() * (max - min + 1)) + min
The function "Math.floor()" is used to get the lowest possible integer value from the formula "Math.random() * (max - min + 1)". The "+ min" appends the minimum value to the result, bringing the generated number down to fit within the given parameters.
Program to Generate a Random Number Between Two Numbers
In the program given below, the minimum and maximum values are taken as input from the user. Then the Math.random()
method is used to get the random number from the passed value. The Math.floor()
returns the nearest integer value.
// Taking input from the user for both the minimum and the maximum values
const mini = parseInt(prompt("Enter a min value: "));
const maxi = parseInt(prompt("Enter a max value: "));
// generating a random number
const a = Math.floor(Math.random() * (maxi - mini + 1)) + mini;
console.log(`Random value between ${mini} and ${maxi} is ${a}`);
Enter a min value: 1
Enter a max value: 100
Random value between 1 and 100 is 87
Conclusion
Games and simulations are two common applications for random number generation. Random number generators can be used to determine game outcomes or to introduce new elements. Random numbers can be used to inject uncertainty and uncertainty into a simulation.
Overall, JavaScript provides a straightforward and effective method for generating random numbers, which is a common requirement in web development. We can generate a random number between max and min using the formula Math.floor(Math.random() * (max - min + 1) + min. The programme has many potential uses, some of which include game development, simulation, testing, and advertising.