Generate an n-digit random number using JavaScript

Today we’ll show you how to generate an n-digit random number using JavaScript. We have multiple ways to get n-digit random numbers but we’ll cover a few of them for demo purposes.

We have already written an article to Convert a String to a Number in JavaScript.

Let’s check out the below examples.

Way to generate an n-digit random number

  1. Generate 6 digit random number
  2. Generate n-digit random number

1. Generate 6 digit random number

Use the following code to generate a 6 digit random number.

Here we have used the Math.random() method to generate the random number and then after substring it for six digit output.

2. Generate n-digit random number

To generate n-digit random numbers, check out the code below.

In the above code, we have used the same Math.random() method to generate the random number then used the toFixed() method for number generation and split it for actual output.

That’s it for today.
Thank you for reading. Happy Coding..!!

You may also like...

Leave a Reply

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