Skip to content

Instantly share code, notes, and snippets.

@GoodBoyNinja
Created June 7, 2021 21:04
Show Gist options
  • Save GoodBoyNinja/a4902693e519ed55eddb718d69d38042 to your computer and use it in GitHub Desktop.
Save GoodBoyNinja/a4902693e519ed55eddb718d69d38042 to your computer and use it in GitHub Desktop.
Generate a random number between a min and a max. Limit the decimal places to a specific amount if you want to. Set decimal places to 0 to return a rounded int.
function genRand(min, max, decimalPlaces) {
// you could add some error checking to make sure all arguments exist
var result = Math.random() * (max - min) + min;
if (decimalPlaces > 0) {
var power = Math.pow(10, decimalPlaces);
var result = Math.floor(result * power) / power;
}
if (decimalPlaces === 0) {
result = Math.round(result);
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment