Skip to content

Rust leading zeros, signs, and zero padding

Use Rust’s numeric 0 flag when you need leading zeros. For example, {:05} formats 42 as 00042, while keeping signs and numeric prefixes in the correct position.

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");

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.

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

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

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.