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

1 Answer

0 votes
#include <stdio.h>
#include <math.h>

/*
    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
        out          - output buffer
        out_size     - size of output buffer

    Example:
        num = 3.14159, width = 5, decimals = 5
        Output → "00003.14159"
*/
void format_decimal_with_zeros(double num, int width, int decimals,
                               char *out, int out_size)
{
    int integer_part = (int)num;
    double fractional_part = num - integer_part;

    // Format integer part with leading zeros
    char int_str[32];
    sprintf(int_str, "%0*d", width, integer_part);

    // Format fractional part (starts with "0.xxx")
    char frac_str[32];
    sprintf(frac_str, "%.*f", decimals, fractional_part);

    // Skip the leading "0" before the decimal point
    snprintf(out, out_size, "%s%s", int_str, frac_str + 1);
}

int main() {
    double num = 3.14159;
    char result[64];

    format_decimal_with_zeros(num, 5, 5, result, sizeof(result));

    printf("Original number: %f\n", num);
    printf("Formatted string: %s\n", result);

    return 0;
}



/*
run:

Original number: 3.141590
Formatted string: 00003.14159

*/

 



answered 10 hours ago by avibootz

Related questions

...