Skip to content

Signs and zero padding

Rust has dedicated numeric flags for signs and zero padding. They are not equivalent to adding a custom 0 fill character because the formatter keeps the sign and numeric prefix in the correct place.

EXAMPLE: CI-CHECKEDTEST ASSERTED · examples/format-output/src/format_pages.rs#format-sign-zero-pad
assert_eq!(format!("{:+}", 42), "+42");
assert_eq!(format!("{:05}", 42), "00042");
assert_eq!(format!("{:+08}", 42), "+0000042");
assert_eq!(format!("{:05}", -42), "-0042");

+ requests an explicit sign for numeric output. Positive values get +; negative values keep -.

Without +, positive and unsigned values normally have no sign.

A leading 0 in the format specification asks numeric formatters to pad to the requested width with zeros. Padding is sign-aware. A positive 42 with width five becomes 00042; a negative -42 becomes -0042.

The width includes the sign. Rust therefore uses one fewer zero when a sign is present.

Do not confuse the zero flag with a fill character

Section titled “Do not confuse the zero flag with a fill character”

{:0>5} and {:05} may look similar for a positive integer, but they are different instructions. 0> means ordinary fill plus right alignment. The numeric 0 flag is sign-aware and knows how to place zeros relative to a sign and alternate base prefix.

When signs or prefixes are possible, use the numeric zero flag rather than imitating it with fill/alignment syntax.

The same rule extends to alternate base prefixes. With #, zero padding goes after 0x, 0b, or 0o and before the digits. The prefix counts toward the total width.

See alternate formatting for prefixes and width, alignment, and fill for non-numeric padding.