How to use Math.round() with Math.random() In Javascript
Using Math.round()
with Math.random()
in JavaScript allows for the generation of random integers by rounding the result of Math.random()
. This is commonly used when a fair rounding to the nearest integer is needed.
Example: The below code uses Math.round() with Math.random() to generate random number.
Javascript
const randomInteger = Math.round(Math.random() * 10); console.log(randomInteger); |
Output
4
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()