How can I 0-pad a number by a variable amount when formatting with std::fmt?

You can use the :0_ format specifier with a variable:

println!("{:0width$}", x, width = width); // prints 001234

Here it is running in the playground

Likewise, if width <= 4, it just prints 1234. If width = 60, it prints:

000000000000000000000000000000000000000000000000000000001234

The format arguments also support ordinals, thus this also works:

println!("{:01$}", x, width);

The documentation for std::fmt has a rundown of the various parameters and modifiers the print_! macros support.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)