The task is to generate an n-Digit random number with the help of JavaScript.
Below two approaches are discussed. In the first example, it uses the minimum and the maximum number of those many digits, while the second one uses the substring concept to trim the digit.
You can also generate random numbers in the given range using JavaScript.
Approach 1: Get the minimum and maximum number of n digits in variable min and max respectively. Then generate a random number using Math.random()(value lies between 0 and 1). Multiply the number by (max-min+1), get its floor value and then add min value to it.
- Example: This example implements the above approach.
<!DOCTYPE HTML><html><head>   Â<title>       ÂGenerate a n-digit number using JavaScript   Â</title>   Â<style>       Âbody {           Âtext-align: center;       Â}       Âh1 {           Âcolor: green;       Â}       Â#neveropen {           Âcolor: green;           Âfont-size: 29px;           Âfont-weight: bold;       Â}   Â</style></head>ÂÂ<body>   Â<h1> Â     Âneveropen Â   Â</h1>   Â<p>        Â     Â<!-- min and max are 5 digit so-->       Â     ÂClick on the button to generate random     Â5 digit number   Â</p>   Â<buttononclick="gfg();">       Âclick here   Â</button>   Â<pid="neveropen">   Â</p>   Â<script>       Âvar up = document.getElementById('GFG_UP');       Âvar down = document.getElementById('neveropen');       Âfunction gfg() {           Âvar minm = 10000;           Âvar maxm = 99999;           Âdown.innerHTML = Math.floor(Math           Â.random() * (maxm - minm + 1)) + minm;       Â}   Â</script></body>ÂÂ</html> - Output:
Approach 2: Use Math.random() method to generate a random number between 0 and 1. Now we will use .substring() method to get a part of the random number after converting it to string.
- Example: This example implements the above approach.
<!DOCTYPE HTML><html>ÂÂ<head>   Â<title>       ÂGenerate a n-digit number using JavaScript   Â</title>   Â<style>       Âbody {           Âtext-align: center;       Â}       Âh1 {           Âcolor: green;       Â}       Â#neveropen {           Âcolor: green;           Âfont-size: 29px;           Âfont-weight: bold;       Â}   Â</style></head>ÂÂ<bodystyle="text-align:center;">   Â<h1style="color:green;">       Âneveropen   Â</h1>   Â<p>       ÂClick on the button to generate random 6 digit number   Â</p>   Â<buttononclick="gfg();">       Âclick here   Â</button>   Â<pid="neveropen">   Â</p>   Â<script>       Âvar down = document.getElementById('neveropen');       Âfunction gfg() {           Âdown.innerHTML = ("" + Math.random()).substring(2, 8);       Â}   Â</script></body>ÂÂ</html> - Output:

