Home > Web Front-end > JS Tutorial > How to Generate Random Whole Numbers Within a Specific Range in JavaScript?

How to Generate Random Whole Numbers Within a Specific Range in JavaScript?

Linda Hamilton
Release: 2024-12-20 04:28:09
Original
219 people have browsed it

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;
}
Copy after login

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;
}
Copy after login

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));
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template