Example Math Code 2

Using Math.random on its own will produce a random number between 0 and 1. However, it may be more useful in certain instamces to generate a random integer value between a certain range.

The following program shows the use of Math.random ( ) to generate a random number between 1 and 6.

<html>
<head>
<script type='text/javascript'>

// This program will produce a random integer between 1 and 6.
// If the + 1 is omitted the random number produced will be
// in the range of 0 to 5.

var Dice ;

Dice = Math.floor((Math.random()*6)+1) ;

alert (Dice) ;

</script>
</head>
<body>
</body>
</html>

Note: Math.floor will round a number down to its nearest Integer.

Using Math.random in JavaScript should always produce a different sequence of values. However, in some programming languages this may not be the case and an additional command such as Randomize may have to be added before the random function.

Next: Character and String Functions