Generate a random n digit number using JavaScript

Let’s learn how to generate a random n digit number using JavaScript. For generating a random number we have many ways and logic. In this article we are mainly using Math.random() which returns a random number between 0 (inclusive), and 10 (exclusive). So, let’s have a look at some methods and try getting some random numbers.

Methods:

  • Generating particular digit number, example 4-digit number
  • Generate n-digit number

1. Generate 4-digit random number (with Min & Max)

There are two ways given below to generate 4-digit random number:

Code for generating 4-digit number is as follows (Method -1):

function fourDigitRandomNum()
{
var min = 1000;
var max = 9999;
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var x= fourDigitRandomNum();
console.log(x);
Sample output: 2912 

Explanation: In this above example we have taken a minimum value i.e 1000 and maximum value i.e 9999 both are of four digit as we are generating 4-digit number, then we have returned the value using functions like Math.floor() function which accepts a floating point number and returns the largest integer less than or equal to the given number and Math.random() function which gives us the random numbers.

Code for generating 4-digit number is as follows (Method – 2):

<script>
function fourDigitRandomNum()
{
return Math.random().toString().substring(2, 6);
}
var x = fourDigitRandomNum();
console.log(x);
</script>
Sample output: 4075

Explanation: Here also we have used Math.random() function with the help of which we can generate random numbers and after that we have used substring() function to get the length of the random number as 4. Similarly, we can generate random numbers of 6 digits, 8 digits or whatever.

2. Generate ‘n’ digit number

Code for generating n digit number is as follows:

<script>
function nDigitRandomNum(digit)
{
return Math.random().toFixed(digit).split('.')[1];
}
var x = nDigitRandomNum(16);
console.log(x);
</script>
Sample Output: 6170281998871858

Explanation: In this code, we have again 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.

So, that’s all for this article. I hope this article was helpful enough.
Thank you.

Leave a Comment