# Rust leading zeros, signs, and zero padding

> Add leading zeros and explicit signs to Rust numbers with format width and sign-aware zero padding, including prefixed hex, binary, and octal.

HTML: https://rustprint.com/format/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.

**Explicit signs and sign-aware zero padding**

```rust
assert_eq!(format!("{:+}", 42), "+42");
assert_eq!(format!("{:05}", 42), "00042");
assert_eq!(format!("{:+08}", 42), "+0000042");
assert_eq!(format!("{:05}", -42), "-0042");
```

## Add leading zeros to a number

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.

## The plus flag

`+` 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

`{: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.

## Zero padding with base prefixes

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](/format/alternate-format/index.md) for prefixes and [width, alignment, and fill](/format/width-alignment-fill/index.md) for non-numeric padding.

## Sources

- [std::fmt sign and zero flags](https://doc.rust-lang.org/std/fmt/#sign00)

## Related RustPrint guides

- [Rust pad and align strings with width and fill](/format/width-alignment-fill/index.md): Pad Rust strings and formatted values with minimum width, left, center, or right alignment, and custom fill characters.
- [Rust format hex with 0x, binary with 0b, and pretty Debug](/format/alternate-format/index.md): Use Rust's # format flag to add 0x, 0b, and 0o prefixes, combine them with zero padding, and request pretty Debug output with {:#?}.
- [Rust format hex, binary, octal, and scientific notation](/format/number-bases/index.md): Format Rust numbers as hex, binary, octal, or scientific notation with std::fmt suffixes, uppercase output, prefixes, width, and zero padding.
