Javascript random number generator in a given range;
A simple snippet to generate a random number in a given range.
example:
randomNum(123,200)
output: 134
randomNum(123,200)
output: 149
Code Explanation:
Math.random() * (1 + max - min)
This code generates a random number between 0 to (1+ max -min)
Here we add an extra one so that we can have the max value too
for example: max = 100, min = 90. so, (1 + 100 - 90) = 11
if the Math.random() returns 0.6857187917646552 * 11 = 7.5429067094112074
as we need a whole number we use:
Math.floor(Math.random() * (1 + max - min))
Which returns 7
Now We add the min value to it which this case is 90. so, 90+7=97 that is in the range of 90 to 100
Min value is added so that we can have a random number between the min and max value;
Math.floor(Math.random() * (1 + max - min)) + min
Comments
Leave a comment
You are not LoggedIn but you can comment as an anonymous user which requires manual approval. For better experience please Login.