How to count the number of digits in an integer with TypeScript

2 Answers

0 votes
/**
 * Counts digits by converting the number to a string.
 * This approach is clear, safe, and widely used in everyday TypeScript code.
 */
function countDigitsString(value: number): number {
  const text: string = value.toString();

  // If negative, ignore the leading '-'
  if (text.startsWith("-")) {
    return text.length - 1;
  }

  return text.length;
}

const number1: number = -12345;
const digits1: number = countDigitsString(number1);

console.log("Number:", number1);
console.log("Digit count (String method):", digits1);



/*
run:

Number: -12345
Digit count (String method): 5

*/

 



answered Jan 7, 2022 by avibootz
edited Aug 13 by avibootz
0 votes
/**
 * Counts digits using Math.log10.
 * Uses the formula: floor(log10(n)) + 1
 * Zero is handled separately because log10(0) is undefined.
 */
function countDigitsLog10(value: number): number {
  const num: number = Math.abs(value);

  if (num === 0) {
    return 1;
  }

  return Math.floor(Math.log10(num)) + 1;
}

const number2: number = 987654321;
const digits2: number = countDigitsLog10(number2);

console.log("Number:", number2);
console.log("Digit count (log10 method):", digits2);


/*
run:

Number: 987654321
Digit count (log10 method): 9

*/

 



answered Jan 7, 2022 by avibootz
edited Aug 13 by avibootz
...