Search code examples
rustformatnumber-formattingpercentage

How can I print the integer part of a floating point number with 2 digits using leading zeros in Rust?


How do I format 5.0 into 05.0%? Using {:02.2} does not seem to work; it does the same as {.2}.


Solution

  • https://doc.rust-lang.org/std/fmt/#width

    fn main() {
        println!("{:04.1}%", 5.0);
    }
    

    prints

    05.0%

    which is padded to a length of 4 characters including the decimal point. Your example would be padded to length 2, but already has length 3, thus nothing changes.