Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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.

like image 569
Fitzsimmons Avatar asked Jan 24 '17 05:01

Fitzsimmons


People also ask

How can I add zero in front of a number in C#?

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.

Does format return a string rust?

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.

What is format macro in Rust?

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.


1 Answers

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.

like image 112
Simon Whitehead Avatar answered Oct 12 '22 09:10

Simon Whitehead