Thursday, November 29, 2012

JavaScript function to get random number between a range

Getting random number in JavaScript

Code:  alert(Math.random())
Getting random number is very easy you can use JavaScript function random() of Math object to get the random number between 0 and 1. For example, above JavaScript statement returns a random number between 0 and 1.

JavaScript function to get random number between 1 and N

//function to get random number from 1 to n
function randomToN(maxVal, floatVal) {
    var randVal = Math.random() * maxVal;
    return typeof floatVal == 'undefined' ? Math.round(randVal) : randVal.toFixed(floatVal);
}

As, you can see in the above JavaScript function, there are two parameters. One for the maximum value(N) up to which random number have to be generated. The second parameter is optional which specifies number of digits after decimal point.If not provided, this function returns integer.

JavaScript function to get random number between a range

    function GenerateRandom(min, max, floatVal) {
        var randVal = min + (Math.random() * (max - min));
        return typeof floatVal == "undifined" ? Math.round(randVal) : randVal.toFixed(floatVal);
    }
The above JavaScript funciton accepts three parameters.The first and second parameter is mandatory while the third is optional. The first and second parameter specifies the range between which the random number has to be generated. The thir parameter is optional which specifies number of floating point digits, if not provided, the above JavaScript function returns integer random number.

No comments:

Post a Comment