Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,844 questions

55,671 answers

573 users

How to generate a random color in HEX format with TypeScript

2 Answers

0 votes
function generateRandomHexColor(): string {
  const hexChars = "0123456789ABCDEF";
  let hex: string = "";

  for (let i: number = 0; i < 6; i++) {
    const index: number = Math.floor(Math.random() * 16);
    hex += hexChars[index];
  }

  return hex;
}

const hexColor: string = generateRandomHexColor();

console.log(`Random HEX Color: #${hexColor}`);


/*
run:

Random HEX Color: #DD381D

*/

 



answered Oct 9, 2025 by avibootz
edited 1 day ago by avibootz
0 votes
/**
 * Generate a random color in HEX format (#RRGGBB).
 * This program demonstrates how numbers and bits are used
 * to produce a valid 24‑bit color value.
 */

/**
 * Create a 24‑bit random integer (0x000000–0xFFFFFF).
 * Math.random() gives a floating‑point number in [0, 1),
 * so multiplying by 0x1000000 (2^24) gives a range of 24 bits.
 */
function randomColorInt(): number {
  // 24 bits → values from 0 to 16,777,215 (0xFFFFFF)
  return Math.floor(Math.random() * 0x1000000);
}

/**
 * Convert a 24‑bit integer into a hex color string.
 * padStart(6, "0") ensures the hex string is always 6 characters.
 */
function intToHexColor(value: number): string {
  const hex: string = value.toString(16);      // Convert number → hex
  const padded: string = hex.padStart(6, "0"); // Ensure 6 hex digits

  return `#${padded}`;
}

/**
 * Produce a random hex color by combining the two functions.
 */
function generateRandomHexColor(): { value: number; hex: string } {
  const value: number = randomColorInt();   // 24‑bit random number
  const hex: string = intToHexColor(value); // Convert to #RRGGBB
  
  return { value, hex };
}

// Run the program
const result = generateRandomHexColor();
console.log("Random 24‑bit value:", result.value);
console.log("Hex color:", result.hex);



/*
run:

Random 24‑bit value: 16130932
Hex color: #f62374

*/

 



answered 1 day ago by avibootz
...