var rand_no = Math.random(); alert(rand_no);
In the code above, the random() method returns the number which we store in the variable rand_no and display through alert().
Click to display a random number.
You’ll notice that each time you click the link a new random number is generated and displayed.
Suppose you want a random number between 1 and 100. How do you get it from the long decimal number thrown up by the random() method?
The first step is to multiply the long decimal random number generated by the random() method with 100.
var rand_no = Math.random(); rand_no = rand_no * 100; alert(rand_no);
Math.ceil(2.456) //gives 3 Math.ceil(46.9) //gives 47 Math.ceil(0.0006) // gives 1
To remove numbers after the decimal and provide us with an integer between 1 and 100, we will pass the random number generated by random() to ceil().
var rand_no = Math.random(); rand_no = rand_no * 100; rand_no = Math.ceil(rand_no); alert(rand_no);
Click to generate a random number between 1 and 100.
The above set of statements can also be shortened to:
var rand_no = Math.ceil(100*Math.random()); alert(rand_no);
What if you want random numbers between 0 and 10?
The question is important. Because if we use the above code, it will simply not work. Since ceil() always returns the next higher integer, all random number that are between 0 and 1 will be converted to 1.
The floor() rounds a number down to the lower integer. Thus:
Math.floor(2.456) //gives 2 Math.floor(46.9) //gives 46 Math.floor(0.0006) // gives 0 Math.floor(1.0006) // gives 1 Math.floor(0.932) // gives 0
But this throws up another problem. Number between 0.9 and 1.0 will all be rounded down (after multiplying with 10) to 9!
The solution lies in multiplying the random number generated by random() with 11 – one number more than the range.
var rand_no = Math.floor(11*Math.random()); alert(rand_no);
To generate random numbers from a given range, follow the steps below:
var rand_no = Math.floor((10-4)*Math.random()) + 5; alert(rand_no);
The code above generates a random number between 5 and 10. Just to prove that this works beautifully click to get a list of 20 random number between 5 and 10
The internal codename for the iPad at Apple was K48. [more...]