7

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 ?

1

3 Answers 3

10

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.

Sign up to request clarification or add additional context in comments.

Comments

8

Just scale the result:

function randomInRange(from, to) {
  var r = Math.random();
  return Math.floor(r * (to - from) + from);
}

1 Comment

Great...Works pretty well...Thanks :)
1
Math.floor(Math.random()*898)+101

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.