Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q1264 How to generate a random integer within and including two limits. For example: 3 & 7. How to randomly generate 3, 4, 5, 6 or 7?

You are here: irt.org | FAQ | JavaScript | Random | Q1264 [ previous next ]

There are three useful methods:

METHOD#1. Hardcode the numbers into the function...

function getRandom()
{
   return (Math.round(Math.random()*(7-3)))+3;
}

myRandomNumber = function getRandom();

METHOD#2. Pass the numbers to the function...

function getRandom(min,max)
{
   return (Math.round(Math.random()*(max-min)))+min;
}

myRandomNumber = function getRandom(3,7);

METHOD#3. Pass the variables to the function...

function getRandom(min,max)
{
   return (Math.round(Math.random()*(max-min)))+min;
}

var myLoNumber = 3;
var myHiNumber = 7;

myRandomNumber = function getRandom(myLoNumber,myHiNumber);

Submitted by Joe Barta

©2018 Martin Webb