/**
* 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
*/