pinalbhatt
7/23/2014 - 9:12 PM

Javascript: Random Number between two integers

Javascript: Random Number between two integers

/*
Javascript: Random Number between two integers
http://blogs.pbdesk.com/javascript-random-number-between-two-integers/

*/
function randomFromTo(from, to){
       return Math.floor(Math.random() * (to - from + 1) + from);
    }
    
//Invocation:
var rnd = randomFromTo(5,20);

/*
And if want to extended your Math Library with this new functionality here is your prototype extension code:
*/
if(!Math.prototype.randomFromTo){
       Math.prototype.randomFromTo = function(from, to){
           return Math.floor(Math.random() * (to - from + 1) + from);
      };
}

//Invocation:
Math.randomFromTo(5,25)