Winthan Aung
Winthan Aung

Reputation: 351

Generating random integer in range that doesn't start at zero

How can I generate numbers between 7 to 10? So far all I've figured out is generating in a range from 0-10:

Math.floor(Math.random()*11)

Upvotes: 20

Views: 26142

Answers (4)

Jordan
Jordan

Reputation: 32532

function getRandom(min, max) {
    return min + Math.floor(Math.random() * (max - min + 1));
}

for(var x = 0; x < 5; x++) {
    console.log(getRandom(7, 10));
}

Upvotes: 67

Soony
Soony

Reputation: 913

7 + Math.floor(Math.random()*4)

Upvotes: 0

Justin Ethier
Justin Ethier

Reputation: 134177

Just say this:

Math.floor(Math.random()*4) + 7

This will generate a random number from 0-3 and then add 7 to it, to get 7-10.

Upvotes: 4

David Titarenco
David Titarenco

Reputation: 33396

Math.floor(7 + Math.random() * 4) will generate numbers from 7 to 10 inclusive.

Upvotes: 22

Related Questions