Skip to content

Width, alignment, and fill

Width tells Rust the minimum number of columns a formatted value should occupy. If the representation is shorter, Rust pads it. If it is already longer, width does not truncate it.

EXAMPLE: CI-CHECKEDTEST ASSERTED · examples/format-output/src/format_pages.rs#page-width-alignment-fill
assert_eq!(format!("|{:<8}|", "rust"), "|rust    |");
assert_eq!(format!("|{:^8}|", "rust"), "|  rust  |");
assert_eq!(format!("|{:>8}|", "rust"), "|    rust|");
assert_eq!(format!("|{:.^8}|", "rust"), "|..rust..|");

Rust uses three alignment characters:

Syntax Meaning
< left-align
^ center
> right-align

The width follows the alignment, so {:>8} means “format this value in at least eight columns and place padding on the left.”

For non-numeric values, the default fill is a space and the default alignment is left. Numeric formatters default to right alignment.

A custom fill character appears immediately before the alignment character:

{:.^8}

That means “center within width 8 and use . for padding.” The fill character and alignment are a pair - a character in that position is only interpreted as fill when an alignment operator follows it.

Width adds padding when output is too short. Precision can shorten some representations. These two controls can be combined, but they solve different problems.

If you need a fixed-looking table column, width and alignment are usually the first tools to reach for. If you need to limit a string or control floating-point decimal places, use precision.

For numbers, 0 is not just a normal fill character. The zero-padding flag is sign-aware and interacts with prefixes such as 0x. Use signs and zero padding when a sign or numeric prefix is involved instead of treating 0 as ordinary fill.