Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random number between two numbers in JavaScript

Is there a way to generate a random number in a specified range with JavaScript ?

For example: a specified range from 1 to 6 where the random number could be either 1, 2, 3, 4, 5, or 6.

like image 428
Mirgorod Avatar asked Feb 10 '11 16:02

Mirgorod


People also ask

How do you generate a random number between two values in JavaScript?

In JavaScript, you can generate a random number with the Math. random() function.

How do you generate a random number between two numbers?

The Excel RANDBETWEEN function returns a random integer between given numbers. RANDBETWEEN is a volatile function recalculates when a worksheet is opened or changed. This formula is then copied down from B5 to B11. The result is random numbers between 1-100.

How do you generate a random number in JavaScript?

Javascript creates pseudo-random numbers with the function Math. random() . This function takes no parameters and creates a random decimal number between 0 and 1. The returned value may be 0, but it will never be 1.


1 Answers

function randomIntFromInterval(min, max) { // min and max included    return Math.floor(Math.random() * (max - min + 1) + min) }  const rndInt = randomIntFromInterval(1, 6) console.log(rndInt)

What it does "extra" is it allows random intervals that do not start with 1. So you can get a random number from 10 to 15 for example. Flexibility.

like image 139
Francisc Avatar answered Oct 15 '22 22:10

Francisc