Javascript: Random Number between two integers

Javascript does has built-in function Math.random() to generate a random number, however the so generated random number is always a floating value between 0 and 1. This may be fine for some requirements but most likely you will end up with a requirement where you will need a random number between two integers. Many other programming languages do have utility for this but in case of Javascript we need to write our own simple  utility function. Below is the simple function which will generate a random number between two numbers ‘form’ and ‘to’:

function randomFromTo(from, to){
       return Math.floor(Math.random() * (to - from + 1) + from);
    }

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);
      };
}

 

With this piece of code we can call the method from the Math Object like this:

Math.randomFromTo(5,25)

Some of you may be curious as to why Math.floor(), instead of Math.round(), is used in the above code. While both successfully round off its containing parameter to an integer within the designated range, Math.floor does so more "evenly", so the resulting integer isn't lopsided towards either end of the number spectrum. In other words, a more random number is returned using Math.floor().

[emc2alert type="info" style="normal" position="bottom" visible="visible" closebtn="0" title="Gist" ]Find this code on my Gist[/emc2alert]

[gist id = "151d0b62501d3413647e" file = "RandomNumber" ]