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
.
You can add leading zeros to an integer by using the "D" standard numeric format string with a precision specifier. You can add leading zeros to both integer and floating-point numbers by using a custom numeric format string.
Functions. The format function takes an Arguments struct and returns the resulting formatted string. The write function takes an output stream, and an Arguments struct that can be precompiled with the format_args! macro.
Macro std::formatCreates a String using interpolation of runtime expressions. The first argument format! receives is a format string. This must be a string literal. The power of the formatting string is in the {} s contained.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With