How to use Math.floor() with Math.random() In Javascript
Using Math.floor() with Math.random() in JavaScript enables the creation of random integers within a defined range. This combination ensures a predictable outcome for applications such as games and simulations.”
Example: Randomly generating integer within a specific range using the Math.floor() method along with the Math.random() method.
Javascript
function random() { let randomNo = Math.floor(Math.random() * 10); console.log(randomNo); } random(); |
Output
3
How to Generate a Random Number in JavaScript ?
JavaScript allows us to generate random numbers using
Math.random()
method
, which return a pseudo-random floating-point number between 0 (inclusive) and 1 (exclusive).
To obtain random integers within a specific range, one often uses a combination of Math.random()
, multiplication, and rounding.
Table of Content
- Using Math.random() method
- Using Math.floor() with Math.random()
- Using Math.ceil() with Math.random()
- Using Math.round() with Math.random()