35

I'm looking to 0-pad a string before I display it to the user, e.g.

let x = 1234;
println!("{:06}", x); // "001234"

However, I'd like the length of the output string to be variable, e.g. it could be set by a command line parameter from the user:

let x = 1234;
let width = 6;
println!("{:0*}", width, x); //fails to compile
// error: invalid format string: expected `'}'`, found `'*'`

Unlike precision, it doesn't seem that 0-padding supports the * for specifying a width.

I'm not looking for solutions that involve manually padding, because it seems awkward to re-implement part of std::fmt.

Fitzsimmons
  • 1,411
  • 1
  • 10
  • 17

1 Answers1

56

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.

Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138