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

1 Answer

0 votes
#include <iostream>
#include <iomanip>
#include <sstream>

using std::stringstream;

/*
    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"
*/
std::string format_decimal_with_zeros(double num, int width, int decimals)
{
    // Split into integer and fractional parts
    int integer_part = static_cast<int>(num);
    double fractional_part = num - integer_part;

    // Convert integer part with leading zeros
    stringstream int_ss;
    int_ss << std::setw(width) << std::setfill('0') << integer_part;
    std::string int_str = int_ss.str();

    // Convert fractional part (starts with "0.xxx")
    stringstream frac_ss;
    frac_ss << std::fixed << std::setprecision(decimals) << fractional_part;
    std::string frac_str = frac_ss.str();

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

int main() {
    double num = 3.14159;

    std::string result = format_decimal_with_zeros(num, 5, 5);

    std::cout << "Original number: " << num << std::endl;
    std::cout << "Formatted string: " << result << std::endl;
}



/*
run:

Original number: 3.14159
Formatted string: 00003.14159

*/

 



answered 3 hours ago by avibootz
...