5

Possible Duplicate:
Generating random numbers in Javascript

Hi..

I want to generate random numbers (integers) in javascript within a specified range. ie. 101-999. How can I do that. Does Math.random() function supports range parameters ?

Community
  • 1
  • 1
Vineet Sharma
  • 797
  • 3
  • 14
  • 25
  • 1
    possible duplicate of [Generating random numbers in Javascript](http://stackoverflow.com/questions/1527803/generating-random-numbers-in-javascript) It covers exactly your question. – Felix Kling Nov 16 '10 at 13:34

3 Answers3

8

Just scale the result:

function randomInRange(from, to) {
  var r = Math.random();
  return Math.floor(r * (to - from) + from);
}
Pointy
  • 405,095
  • 59
  • 585
  • 614
7

The function below takes a min and max value (your range).

function randomXToY(minVal,maxVal)
{
  var randVal = minVal+(Math.random()*(maxVal-minVal));
  return Math.round(randVal);
}

Use:

var random = randomXToY(101, 999);

Hope this helps.

Evan Mulawski
  • 54,662
  • 15
  • 117
  • 144
1
Math.floor(Math.random()*898)+101
Andy E
  • 338,112
  • 86
  • 474
  • 445
SK-logic
  • 9,605
  • 1
  • 23
  • 35