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

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"
*/
fn format_decimal_with_zeros(num: f64, width: usize, decimals: usize) -> String {

    // Split into integer and fractional parts
    let integer_part = num.trunc() as i64;
    let fractional_part = num - integer_part as f64;

    // Format integer part with leading zeros
    let int_str = format!("{:0width$}", integer_part, width = width);

    // Format fractional part (starts with "0.xxx")
    let frac_str = format!("{:.*}", decimals, fractional_part);

    // Remove the leading "0" before the decimal point
    format!("{}{}", int_str, &frac_str[1..])
}

fn main() {
    let num = 3.14159;

    let result = format_decimal_with_zeros(num, 5, 5);

    println!("Original number: {:.5}", num);
    println!("Formatted string: {}", result);
}



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

 



answered 18 hours ago by avibootz

Related questions

...