Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate random number with js from range starting from 1?

I've been using this code to generate a random number with js:

var max = 10;
Math.floor( Math.random() * ( max + 1 ) );

From what I understand that will generate a number from 0 to 10, but what if I want to generate a random number from 1 to 10? or from 5 to 10?

like image 423
slemdx Avatar asked Dec 06 '22 21:12

slemdx


2 Answers

try this:

function getRandomInt(min, max){
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
like image 71
DrStrangeLove Avatar answered Feb 04 '23 07:02

DrStrangeLove


You do from 0 to 9, then you add one to the result.

like image 43
Sword22 Avatar answered Feb 04 '23 06:02

Sword22