5

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?

0

3 Answers 3

15

try this:

function getRandomInt(min, max){
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

If you want to start from x instead of 0, then:

  1. Subtract x from max
  2. Do everything else as normal
  3. Add x to the result

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.