println! to print a 2 digit integer

Viewed 208

I would like println! to turn my integer into a 2 digit number, adding a 0 in the front if needed.

fn main() {
    println!("{:}", 7);
    println!("{:}", 12);
}

the expected result should be:

07
12

Any format parameters to be used here or should I create a specific Display trait in this case?

1 Answers

You can set the leading zeros like so:

println!("{:02}", 7);

You can also check the different formatting possibilities in the documentation:

assert_eq!(format!("Hello {:+}!", 5), "Hello +5!");
assert_eq!(format!("{:#x}!", 27), "0x1b!");
assert_eq!(format!("Hello {:05}!", 5),  "Hello 00005!");
assert_eq!(format!("Hello {:05}!", -5), "Hello -0005!");
assert_eq!(format!("{:#010x}!", 27), "0x0000001b!");
Related