Skip to content

Instantly share code, notes, and snippets.

@jpetto
Created August 25, 2012 17:13
Show Gist options
  • Save jpetto/3468066 to your computer and use it in GitHub Desktop.
Save jpetto/3468066 to your computer and use it in GitHub Desktop.
JavaScript rounding/random numbers
// declare our variables
var r, random, max = 20;
// get a random number between 0 (inclusive) and 1 (exclusive)
r = Math.random();
console.log(r);
// get a random number less than the maximum
random = max * r;
console.log(random);
// round the random number in a few ways
console.log(Math.round(random));
console.log(Math.ceil(random));
console.log(Math.floor(random));
// get the integer value of our random number, adding 1 to make sure we can hit the upper bound (20)
random = Math.floor(random + 1);
console.log(random);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment