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

2 Answers

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
        len   - total width of the integer part (zero‑padded)

    Returns:
        A formatted string such as "00003.14159"

    Example:
        num = 3.14159, len = 5
        Output → "00003.14159"
*/

function FormatDecimalWithZeros(num, len) {
  // Convert number to string and split into integer and decimal parts
  const [intPart, decPart] = String(num).split('.');

  // Pad the integer part with leading zeros
  const padded = intPart.padStart(len, '0');

  // Reattach decimal part if it exists
  return decPart ? `${padded}.${decPart}` : padded;
}

const result = FormatDecimalWithZeros(3.14159, 5);

console.log("Original number:", 3.14159);
console.log("Formatted string:", result);


/*
run:

Original number: 3.14159
Formatted string: 00003.14159

*/

 



answered 1 day ago by avibootz
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, width, decimals) {

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

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

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

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

const num = 3.14159;

const result = 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 21 hours ago by avibootz

Related questions

...