To generate a 6-digit random number in JavaScript, use Math.floor(100000 + Math.random() * 900000). This gives you a whole number between 100000 and 999999 (inclusive). For a version that can include leading zeros (like for OTPs or PINs), use String(Math.floor(Math.random() * 1000000)).padStart(6, '0'). This guide walks through both methods, explains how they work, and covers common pitfalls like floating-point precision and security.
What You’ll Need
- A modern web browser (Chrome, Firefox, Safari, Edge) or Node.js installed
- A text editor or browser console to run the code
- Basic familiarity with JavaScript variables and functions
Step-by-Step
- Understand the core formula. The standard way to get a random integer in a range is
Math.floor(Math.random() * (max - min + 1)) + min. For a 6-digit number, min = 100000 and max = 999999. That givesMath.floor(Math.random() * 900000) + 100000. - Write the basic generator. In your JavaScript file or console, type:
const randomSixDigit = Math.floor(100000 + Math.random() * 900000); console.log(randomSixDigit);Each run produces a new integer from 100000 to 999999.
- Test it in the browser console. Open your browser’s developer tools (F12 or Ctrl+Shift+I on Windows, Cmd+Option+I on Mac), go to the Console tab, paste the code, and press Enter. You’ll see a random 6-digit number.
- If you need leading zeros, use padStart. For example, a PIN like ‘042713’ is still 6 digits but starts with zero. Use:
const randomWithZero = String(Math.floor(Math.random() * 1000000)).padStart(6, '0'); console.log(randomWithZero);This generates a number from 0 to 999999 and pads it to 6 characters.
- Wrap it in a reusable function. To call it multiple times, define:
function getSixDigitNumber() { return Math.floor(100000 + Math.random() * 900000); } console.log(getSixDigitNumber());For the padded version, use
return String(Math.floor(Math.random() * 1000000)).padStart(6, '0');. - Use it in a real scenario (e.g., OTP). For a one-time password, you might want a string:
function generateOTP() { return String(Math.floor(Math.random() * 1000000)).padStart(6, '0'); } const otp = generateOTP(); console.log('Your OTP is: ' + otp);This is fine for non-security-critical demos.
- For cryptographic security, use crypto.getRandomValues. If the number is for authentication or tokens, use the Web Crypto API:
function secureSixDigit() { const array = new Uint32Array(1); window.crypto.getRandomValues(array); return String(100000 + (array[0] % 900000)); } console.log(secureSixDigit());In Node.js, use
require('crypto').randomInt(100000, 1000000).
Common Mistakes
- Using Math.round() instead of Math.floor() – Math.round() can give you 100000 or 1000000 in edge cases, breaking the 6-digit requirement. Always use Math.floor().
- Forgetting the +100000 offset – If you write
Math.floor(Math.random() * 900000)you get numbers from 0 to 899999, which may have fewer than 6 digits. - Not handling leading zeros – If you need a string like ‘001234’, a plain number will drop the zeros. Use padStart.
- Using Math.random() for security – Math.random() is not cryptographically secure. For passwords or tokens, use crypto.getRandomValues or Node’s crypto module.
- Off-by-one errors – The range 100000 to 999999 has 900000 possible values. Multiplying by 900000 and adding 100000 is correct. Multiplying by 899999 would exclude 999999.
Tips
- Test the range – Run the code 100 times in a loop and log the min and max to ensure they stay within 100000–999999.
- Use a function for reusability – Instead of repeating the formula, define a function once and call it where needed.
- For strings, always padStart – Even if you think you don’t need zeros, it’s safer to pad to avoid unexpected short values.
- In Node.js, use crypto.randomInt – It’s simpler and secure:
crypto.randomInt(100000, 1000000)returns a number in that range. - Consider using a seed for testing – If you need reproducible numbers (e.g., for unit tests), use a seeded pseudo-random generator library, but for production, stick to the built-in methods.
Troubleshooting
- I get numbers with fewer than 6 digits. – You likely forgot the +100000. Check your formula:
Math.floor(100000 + Math.random() * 900000). - I get 1000000 occasionally. – This happens if you use
Math.ceil()orMath.round(). Switch toMath.floor(). - My number is always the same. – If you’re running in a loop without delay, Math.random() may produce the same value in some old browsers? Actually, it shouldn’t, but if you’re using a seed, that’s the cause. Also, check if you’re reusing a variable incorrectly.
- In Node.js, window.crypto is not defined. – Use the global
cryptoobject (available in Node 19+) or require(‘crypto’).randomInt. - The padded version gives ‘000000’ sometimes. – That’s valid if you want 000000, but if you need at least 100000, use the offset formula and then pad if needed.
Frequently Asked Questions
Can I generate a 6-digit number with Math.random() alone?
Yes, but you must combine it with Math.floor() and an offset. Math.random() alone gives a decimal between 0 and 1, so you need to scale it.
How do I get a 6-digit number as a string?
Use String(Math.floor(100000 + Math.random() * 900000)) or the padStart method for leading zeros.
Is Math.random() safe for generating OTPs?
No. Math.random() is not cryptographically secure. Use crypto.getRandomValues in browsers or crypto.randomInt in Node.js for security-sensitive purposes.
What is the difference between randomInt and Math.random()?
randomInt (Node.js) is cryptographically secure and gives a uniform integer in a range. Math.random() is faster but less secure and can have slight biases.
How can I generate a random 6-digit number without repeating digits?
That’s a different problem. You’d need to shuffle digits 0-9 and pick the first 6, but that’s more complex. For most purposes, repeating digits are fine.
Can I generate a 6-digit number in a single line?
Yes: const n = Math.floor(100000 + Math.random() * 900000); is one line.
Related
- Convert Table Back to Range in Excel: 2 Quick Ways
- Shortcut to Go Back? Browser & App Answers
- Google Sheets Query Compare Dollar Values
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Page Break in Excel Shortcut: Insert and Adjust BreaksIn Excel for Microsoft 365 on Windows, select the row, column, or cell where the printed page should…
- Hide Column Headers in Power BI: Table & MatrixTo hide column headings in a Power BI table, select the visual, open Format visual > Visual >…
- Split Feature in SOLIDWORKS: What It Does and HowThe SOLIDWORKS Split feature divides one solid part into multiple separate solid bodies, using a plane, face, or…
- Excel Time Difference Between Two Dates and Times ExplainedTo find the elapsed time between two date-and-time values in Excel, subtract the earlier value from the later…
- Excel Template for Tracking Monthly ExpensesThe best Excel template for tracking monthly expenses is a simple table with columns for Date, Category, Description,…
- Generate Single Digit Random Number in JavaTo generate a single digit random number (0–9) in Java, use ThreadLocalRandom.current().nextInt(10) for the simplest and most modern…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.