CancelImage Upload

How to produce random numbers in JavaScript

Producing random numbers in JavaScript is a rather complicated process, when compared to most programming languages, such as PHP, where only a simple rand() definition is required to return a random number.

As mentioned this process requires a bit more programming in JavaScript. This is mainly because the JavaScript random number function returns a random float between 0 and 1:

alert(Math.random());

However, there is a simple way to produce a whole number equivalent from this float. First we shall multiple the random number times 10 (or 100, 1000, etc, if you want the random number to be between 1 and 100 or 1000), then we will round it down to lower number:

var randomNumber = 10 * Math.random();

randomNumber = Math.floor(randomNumber);


In practice this would look as follows:

<html>
<head>
<title>How to calculate the square route of a number in JavaScript</title>
<script language="JavaScript">

function randomNumber()
{

      var randomNumber = 10 * Math.random();

      randomNumber = Math.floor(randomNumber);

      alert(randomNumber);

}

</script>
</head>
<body onload="javascript:randomNumber();">

</body>
</html>


Login
Want to leave a comment?

No problem. Just enter your email and password below.


register | home | reminder

myDesignTool Networking • www.mydesigntool.cominfo@mydesigntool.com