Javascript Math Reference : Math.random

Javascript Math.random


The Math.random takes does not take any argument and returns a random number between 0 and 1.

<html>
<body>
<script type="text/javascript">
<!--

/*
********************************************************
Example - Usage of Math.random
********************************************************
*/

var x = Math.random(); // A random number between 0 and 1
document.writeln ("<br />Random Number between 0 and 1: " + x );

 //-->
</script>
</body>
</html>



Try this example online here .



It is often required to find a random numeber between, say 0 to 10. How to do that ? All we do is multiply the returned result by 10 to get the random number between 0 and 10. Look at the following example which prints 10 random numbers between 0 and 10.

<html>
<body>
<script type="text/javascript">
<!--

/*
********************************************************
Example - Usage of Math.random
********************************************************
*/

for (i=0; i<=9; i++)
{
x = Math.random()*10; 
document.writeln ("<br />Random Number between 0 and 10: " + x);
}
 //-->
</script>
</body>
</html>



Try this example online here .



A typical output looks like
Random Number between 0 and 10: 7.743211425929848
Random Number between 0 and 10: 0.7056276518774696
Random Number between 0 and 10: 9.231555257045041
Random Number between 0 and 10: 0.33005140798325394
Random Number between 0 and 10: 7.22913748778844
Random Number between 0 and 10: 2.847247377972332
Random Number between 0 and 10: 9.219032827412834
Random Number between 0 and 10: 5.978896927307241
Random Number between 0 and 10: 8.50390484138096
Random Number between 0 and 10: 1.4229072921192354 


You could potentiall use the round function if you do not like the decimal places as in

x = Math.round(Math.random()*10);  
 


Try making the above change to see the result.