Open In App

How to generate a n-digit number using JavaScript?

Last Updated : 25 Jun, 2024
Suggest changes
Share
Like Article
Like
Report

The task is to generate an n-Digit random number with the help of JavaScript.

You can also generate random numbers in the given range using JavaScript.

Below are the approaches to generate a n-digit number using JavaScript:

Using Math.random()

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 a min value to it.

Example: The example below shows how to generate a n-digit number using JavaScript.

HTML
<!DOCTYPE HTML> <html> <head> <title> Generate a n-digit number using JavaScript </title> <style>  body {  text-align: center;  }  h1 {  color: green;  }  #geeks {  color: green;  font-size: 29px;  font-weight: bold;  }  </style> </head> <body> <p> <!-- min and max are 5 digit so--> Click on the button to generate random 5 digit number </p> <button onclick="gfg();"> click here </button> <p id="geeks"> </p> <script>  let up = document.getElementById('GFG_UP');  let down = document.getElementById('geeks');  function gfg() {  let minm = 10000;  let maxm = 99999;  down.innerHTML = Math.floor(Math  .random() * (maxm - minm + 1)) + minm;  }   </script> </body> </html> 

Output:

imp2i1
Output

Math.random() Method and .substring() Method

Math.random() method use .substring() method to generate a random number between 0 and 1. Now we will use to get a part of the random number after converting it to string.

Example: The example shows How to generate a n-digit number using Math.random() Method and .substring() Method.

HTML
<!DOCTYPE HTML> <html> <head> <title> Generate a n-digit number using JavaScript </title> <style>  body {  text-align: center;  }  h1 {  color: green;  }  #geeks {  color: green;  font-size: 29px;  font-weight: bold;  }  </style> </head> <body style="text-align:center;"> <p> Click on the button to generate random 6 digit number </p> <button onclick="gfg();"> click here </button> <p id="geeks"> </p> <script>  let down = document.getElementById('geeks');  function gfg() {  down.innerHTML = ("" + Math.random()).substring(2, 8);  }   </script> </body> </html> 

Output:

imp2i2
Output

Similar Reads