Home >Web Front-end >JS Tutorial >How to Generate Random Whole Numbers Within a Specific Range in JavaScript?
Generating Random Whole Numbers in a Specified Range in JavaScript
In JavaScript, generating random numbers within a specified range can be achieved using two core methods: getRandomArbitrary() and getRandomInt().
getRandomArbitrary()
This method generates a floating-point number within a given range. It takes two parameters, min and max, and returns a number between min (inclusive) and max (exclusive).
function getRandomArbitrary(min, max) { return Math.random() * (max - min) + min; }
getRandomInt()
This method generates a random integer within a given range. It takes two parameters, min and max, and returns an integer between min (inclusive) and max (inclusive).
function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; }
Implementation
For example, if you want to generate random numbers between 4 and 8 inclusive, you can use either method as follows:
// Using getRandomArbitrary() console.log(getRandomArbitrary(4, 8)); // Using getRandomInt() console.log(getRandomInt(4, 8));
The above is the detailed content of How to Generate Random Whole Numbers Within a Specific Range in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!