How to express a decimal number as a fixed-length string with leading zeros in TypeScript

1 Answer

0 votes
/*
    format_decimal_with_zeros
    -------------------------
    Converts a floating‑point number into a fixed‑length string with
    leading zeros on the integer part.

    Parameters:
        num          - the decimal number to format
        width        - total width of the integer part (zero‑padded)
        decimals     - number of digits after the decimal point

    Returns:
        A formatted string such as "00003.14159"

    Example:
        num = 3.14159, width = 5, decimals = 5
        Output → "00003.14159"
*/
function formatDecimalWithZeros(num: number, width: number, decimals: number): string {

    // Split into integer and fractional parts
    const integer_part: number = Math.trunc(num);
    const fractional_part: number = num - integer_part;

    // Format integer part with leading zeros
    const int_str: string = integer_part.toString().padStart(width, "0");

    // Format fractional part (starts with "0.xxx")
    const frac_str: string = fractional_part.toFixed(decimals);

    // Remove the leading "0" before the decimal point
    return int_str + frac_str.substring(1);
}

const num: number = 3.14159;

const result: string = formatDecimalWithZeros(num, 5, 5);

console.log("Original number:", num.toFixed(5));
console.log("Formatted string:", result);



/*
run:
             
Original number: 3.14159
Formatted string: 00003.14159
         
*/

 



answered 19 hours ago by avibootz

Related questions

...