Sunday, 10 January 2016

JavaScript - generate random integers between 2 values


To generate random values, JavaScript provides Math.random() method. This method generates values in the range 0.0 and 1.0, 1.0 excluded. We can use this function according to our requirements.

Here , if I give an example of a six sided dice. we would need a random number between 1 to 6 , both included.

The formula is Math.floor( lower +  Math.random() * upper ).  lower is the starting value and is called shifting value. upper is the maximum value and is called scaling value. Here is the complete code.

<?xml version="1.0" encoding="utf-8" ?>
<html>
<head>
<title> Generate Random Numbers </title>
<script type="text/javascript">
<!--

function getRandom()
{
var ran = Math.floor( 1 + Math.random() * 6);
window.alert(" you got " + ran);
}

// -->
</script>
</head>
<body>
<input type="button" value="next number"                                          onclick="getRandom()" />
</body>
</html> 

Note : If you omit the floor function, it will give you float values and also values between 6 and 7, which is not the requirement. However, if you require float values you can skip floor function and check if the value is > 6 then make it back to 6 before it is displayed.


I hope it was useful  :) 

No comments:

Post a Comment