10

I know there's several questions on this, but I'm struggling to find out how to use Math.random to get random numbers between two high integers?

So, for example, between 50 and 80. I thought this would work...

'left': Math.floor((Math.random() * 80) + 50) + '%'

Any ideas?

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
John the Painter
  • 2,495
  • 8
  • 59
  • 101
  • 2
    possible duplicate of [Generate random value between two numbers in Javascript](http://stackoverflow.com/questions/4959975/generate-random-value-between-two-numbers-in-javascript) – ILikeTacos Sep 20 '13 at 16:05
  • Maybe `* 30` instead of `* 80` ? – Aleks G Sep 20 '13 at 16:05
  • 1
    Generate a number between 0 and 30 then add 50 to it. – Kevin B Sep 20 '13 at 16:08
  • 1
    possible duplicate of [Generating random numbers in Javascript in a specific range?](http://stackoverflow.com/questions/1527803/generating-random-numbers-in-javascript-in-a-specific-range) –  Feb 01 '15 at 02:56

3 Answers3

33

Assuming the range is inclusive on both ends:

function getRandomInt (min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
General Grievance
  • 4,555
  • 31
  • 31
  • 45
kayz1
  • 7,260
  • 3
  • 53
  • 56
23

You need to know the range of the random.

Between 50 and 80, the range is 30 (80 - 50 = 30), then you add 1.

Therefor, the random would look like this :

Math.floor(Math.random() * 31) + 50
Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75
2

Here consider your min=50 and max = 80 refer below code:

var number = Math.floor(Math.random() * (max - min) + min);

This will solve your problem. You can try any range by changing min and max.

naren
  • 105
  • 2
  • 13