How to generate an 8 digits random number in JavaScript

2 Answers

0 votes
// Function to generate a random integer in an inclusive range [min, max]
function getRandom8DigitNumber() {
  const min = 10000000;
  const max = 99999999;

  return Math.floor(Math.random() * (max - min + 1)) + min;
}

for (let i = 0; i < 10; i++) {
  console.log(getRandom8DigitNumber());
}



/*
run:

34765181
19668559
22407614
53350819
27685085
62013631
44927658
54487864
35401027
97168507

*/


 



answered Apr 28, 2016 by avibootz
edited Oct 2 by avibootz
0 votes
/**
 * Utility module for generating random 8-digit numbers and string codes.
 */

/**
 * Generates a random 8-digit integer between 10,000,000 and 99,999,999 (inclusive).
 * Guaranteed to start with a non-zero digit (1-9).
 *
 * @returns {number} An 8-digit positive integer.
 */
function generate8DigitNumber() {
  const min = 10000000;
  const max = 99999999;
  
  // Math.random() returns a value in [0, 1).
  // Multiplying by (max - min + 1) covers the full range size (90,000,000 values).
  // Math.floor truncates decimals to yield an inclusive integer in [10000000, 99999999].
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

/**
 * Generates an 8-character numeric string between "00000000" and "99999999".
 * Preserves leading zeros using String.prototype.padStart().
 *
 * @param {boolean} [secure=false] - Whether to use Cryptographically Secure PRNG (crypto API).
 * @returns {string} An 8-character numeric string.
 */
function generate8DigitCode(secure = false) {
  let rawValue;

  if (secure) {
    // Web Crypto API / Node.js crypto module
    // Generate a 32-bit unsigned integer (range 0 to 4,294,967,295)
    const array = new Uint32Array(1);
    crypto.getRandomValues(array);
    
    // Scale down to [0, 99999999] without modulo bias
    rawValue = array[0] % 100000000;
  } else {
    // Standard Math.random() for non-security use cases
    rawValue = Math.floor(Math.random() * 100000000);
  }

  // Convert to string and pad with leading zeros up to 8 characters
  return String(rawValue).padStart(8, '0');
}

// ==========================================
// Example Execution & Usage
// ==========================================

// 1. Standard mathematical integer [10000000 to 99999999]
const randomInt = generate8DigitNumber();
console.log(`Generated 8-digit integer: ${randomInt}`);

// 2. Standard string code [00000000 to 99999999] preserving leading zeros
const randomCode = generate8DigitCode();
console.log(`Generated 8-digit string code: ${randomCode}`);

// 3. Cryptographically secure code (for OTPs, PINs, or security tokens)
const secureCode = generate8DigitCode(true);
console.log(`Generated secure 8-digit OTP code: ${secureCode}`);



/*
run:

Generated 8-digit integer: 36526649
Generated 8-digit string code: 96134620
Generated secure 8-digit OTP code: 79264053

*/


 



answered Oct 2 by avibootz
...