I've got this function:
Number.random = function(minimum, maximum, precision) {
minimum = minimum === undefined ? 0 : minimum;
maximum = maximum === undefined ? 9007199254740992 : maximum;
precision = precision === undefined ? 0 : precision;
var random = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
return random;
}
Right now precision is not implemented, does anyone have any good ideas on how I can implement it? The purpose of the precision option is to give you a fixed number of multiple decimal places out, e.g.:
// A number from 0 to 10 that will always come back with two decimal places
Number.random(0, 10, 2); // 3.14
Try this:
Number.random = function(minimum, maximum, precision) {
minimum = minimum === undefined ? 0 : minimum;
maximum = maximum === undefined ? 9007199254740992 : maximum;
precision = precision === undefined ? 0 : precision;
var random = Math.random() * (maximum - minimum) + minimum;
return random.toFixed(precision);
}
It uses .toFixed() function to set the precision
Demo: http://jsfiddle.net/2rFW8/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With