| by Arround The Web | No comments

Generating Random Whole Numbers in JavaScript in a Specific Range

Random numbers are numbers that are generated/created in a random and non-pattern-following manner. They are frequently used in computer programming for various applications, including generating random password characters, mimicking random game events, and creating unique IDs.

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:

function myFunction(myMin, myMax) {

return Math.floor( (Math.random() * (myMax - myMin)) + myMin);

}

Call the function and pass the interval to generate random numbers between “1” and “100”:

let myResult = myFunction(1, 100);

Finally, print the random generated numbers on the console:

console.log("Random Number Between 1 and 100 is : (" + myResult + ")");

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 x = prompt('Enter the Minimum Number : ', '');

var y = prompt('Enter the Maximum Number : ', '');

Define a function for generating random numbers using the Math.random() method with the Math.floor() method:

function myFunction(myMin, myMax) {

return Math.floor( (Math.random() * (myMax - myMin)) + myMin);

}

Call the function to generate random whole numbers between the specified range:

console.log("Random Number Between set interval is " + myFunction(x, y));

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.

Share Button

Source: linuxhint.com

Leave a Reply