Categories
JavaScript Answers

How to generate a random number of fixed length using JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *