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
Use the following code to generate a 6 digit random number.
function getSixDigitRandom() {
return Math.random().toString().substring(2, 8);
}
getSixDigitRandom(); // Output: 407578
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.
function getRandomNumber(digit) {
return Math.random().toFixed(digit).split('.')[1];
}
getRandomNumber(16); // Output: 7170981998871888
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..!!