Creating a random number inside a range in JavaScript
To generate a random number in the JavaScript, you can just use default random
method on Math
object:
Math.random();
The above code will generate some random number between 0 and 1 (inclusive of 0, but not 1).
If you only want an integer out of the random method, use the floor
method of Math
object
Math.floor(Math.random());
But the above code will generate single integer, that's 0.
Generate a random number between 0 and 9(both inclusive)
As you know Math.random()
will give you a number between 0 and 0.999999...
So multiplying it with 10 will give a number between 0 and 9.99999....
Then use Math.floor
to convert the obtained number to integer i.e., the following code will give you any of the 10 integers from 0 to 9
Math.floor(Math.random()*10)
Generate random number between 1 and 10
From the above code it's obvious that you can add 1 to it to generate a random number between 1 and 10.
Math.floor(Math.random()*10)+1
// or
Math.floor((Math.random()+1)*10)
Similarly Math.floor(Math.random()*500)+1
will give you a number between 1 and 500
Use Math.ceil()
to even simplify the expression:
Math.ceil(Math.random() * 10)
If you use Math.round(Math.random() * 10)
, you will get any integer between 0 and 10, including both 0 and 10. So you can get any number out of 11 possible integers, if you use Math.round
.
Last Updated on
Comments