Generating Random Whole Numbers in JavaScript in a Specific Range
This post will discuss the procedure for generating random whole numbers in a specific range in JavaScript.
How to Generate Random Whole Numbers in a Specific Range in JavaScript?
To generate random whole numbers in a specific range, use the built-in “random()” method of the “Math” object with the “floor()” method. The “Math.random()” method gives a random number as an output between 0 (inclusively) and 1 (exclusively). While the “Math.floor()” method rounds a decimal number down to the nearest/closest whole number.
Example 1: Generate Random Whole Numbers in JavaScript in the Static Interval
First, define a function called “myFunction()” with two parameters, “myMin” and “myMax” that indicate the specified interval for generating a random number between it:
Call the function and pass the interval to generate random numbers between “1” and “100”:
Finally, print the random generated numbers on the console:
It can be seen that every time the page is reloaded, a random whole number is generated:
Example 2: Generate Random Whole Numbers Using User-Defined Intervals
First, create two variables, “x” and “y” that will store the input from the user to set the interval for generating random whole numbers:
var y = prompt('Enter the Maximum Number : ', '');
Define a function for generating random numbers using the Math.random() method with the Math.floor() method:
Call the function to generate random whole numbers between the specified range:
Output
We have provided all the necessary information relevant to generating random whole numbers in a specific range in JavaScript.
Conclusion
To generate random whole numbers within the specific range in JavaScript, use the “Math.random()” method with the “Math.floor()” method. It is the most commonly used approach for generating random numbers within a particular range. In this post, we discussed the procedure to generate random whole numbers in a specific range in JavaScript.
Source: linuxhint.com