20

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)
3
  • 2
    asked soooo many times previously.... Commented Jul 15, 2011 at 2:43
  • 6
    And the difference between 7 (which you want) and 0 (which you can generate) is how much? Commented Jul 15, 2011 at 2:50
  • The more comments of S.Lott's that I read, particularly the late-night ones, the more I like him. Commented Jul 15, 2011 at 3:19

4 Answers 4

67
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));
}
Sign up to request clarification or add additional context in comments.

5 Comments

+1 for making it a general purpose function based on min, max.
multiplying random by (max-min) doesn't give you the range you want. Min needs to be a sort of "b" in the metaphorical mx+b here.
@NullVoxPopuli, have you tried it? 43 satisfied customers so far, and I just checked the distribution range on it and it looks right to me. Here's a fiddle: jsfiddle.net/UCX9c/1
oh hey, I didn't see the min at the beginning of that. lol. I thought you were just doing random() * max-min
Ah, gotcha. Interesting to think of a random number within a range as the slope of a line. I tend to think of it as a set instead. Cool mental trick though. I'm sure a math person would laugh at me.
22

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

Comments

4

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.

Comments

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

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.