Hello All
Have you ever needed to create random number in JavaScript?
No.
In C#, creating random number is simple and provides multiple options. Random class is used for the same, it’s Next method used to create random number. It also takes min and max value as parameter to create a random number in a range.
In Javascript it is more simple :). Let’s see that
Math.random is used to create a random number. But it returns a decimal numal number between between 0 (including) to 1(excluding). Let’s see that
function displayRandom() { alert(Math.random()); }
It will create different number each time. So if you want to create a random number say upto 10000 then you can get it by simply writing
var randomnumber = Math.random() * 10000;
Pretty simple Right!!
But it will always create a number less than 10000 (till 9999.999..) and if you take the integer part then the max value you will get 9999. But what if want inclusive of 10000?
Then you can leverage the other method Math.ceil which generates the ceiling number as
Math.ceil(6.0001)
Math.ceil(6.203)
Math.ceil(6.0001)
Math.ceil(6.9001)
For all you will get 7. So if you write the original method as
function displayRandom() { alert(Math.ceil(Math.random())); }
You will get the number between 0 to 10000 both inclusive. You can also use Math.floor or Math.abs to have your own logic for getting random number in a range.
This is small post but I found it bit interesting and useful sometime.
Cheers,
Brij