Sometimes, we want to generate a random number of fixed length using JavaScript.
In this article, we’ll look at how to generate a random number of fixed length using JavaScript.
How to generate a random number of fixed length using JavaScript?
To generate a random number of fixed length using JavaScript, we can use the Math.floor
and Math.random
methods.
For instance, we write
console.log(Math.floor(100000 + Math.random() * 900000));
to generate a 6 digit number with
100000 + Math.random() * 900000
Then we get rid of the decimals by returning the floor of the number with Math.floor
.
Conclusion
To generate a random number of fixed length using JavaScript, we can use the Math.floor
and Math.random
methods.