Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a Random Number with Precision in JavaScript

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
like image 898
Kirk Ouimet Avatar asked Dec 25 '22 10:12

Kirk Ouimet


1 Answers

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/

like image 173
Yuriy Galanter Avatar answered Dec 28 '22 10:12

Yuriy Galanter