There are many ways to generate a random integer with javascript. One commonly used method is using the Math.random()
method. It returns a floating-point, pseudo-random number between 0 and 1 (e.g. 0.253704142109308443). To get a random integer, one can pass the Math.random()
as argument to the parseInt()
method. For example:
var int = parseInt((Math.random() * 100), 10)
In the above code the Math.random()
method returns a random integer between 0 and 1. To convert that to a random number up to 100, multiply it by 100. So if you want a random number up to 10, multiply it by 10. To get an integer from result, the value is passed to the parseInt()
method. The second argument in the parseInt()
method is a radix of 10 that indicates to convert from a decimal number.
To get a random integer within a specific range you can use the following format instead:
parseInt((Math.random() * (max - min + 1)), 10) + min;
So if you wanted a random integer between 50 and 100 the code would be:
parseInt((Math.random() * (100 - 50 + 1)), 10) + 50;
You can easily create a random lottery number by using the above code in a loop.