Posted By

Jamie on 07/21/10


number random generator function integer

Versions (?)

Random Number (Integer) Generator

 / Published in: JavaScript

Simple function to return a value between the minValue and the maxValue.

  1. // Random integer between
  2. function randomIntegerBetween(minValue,maxValue){
  3. return Math.floor(Math.random() * (maxValue - minValue + 1)) + minValue;
  4. }

Report this snippet  


RSS Icon Subscribe to comments
Posted By: mwalsh on August 1, 2010

Math.min is unnecessary but doesn't actually hurt the calulation.

Math.round, on the other hand, skews the numbers heavily away from the min and max values, you'll hardly ever get them.

After some quick testing, this seems to work much better:

Math.floor(Math.random() * (maxValue - minValue + 1)) + minValue;

Posted By: Jamie on August 19, 2010

Thanks for the feedback mwalsh! Like most code, this was written out of utility, and it's very cool of you to help me refine it. I've updated the snippet. Thanks!

You need to login to post a comment.