Skip to content

Binary, octal, hexadecimal, and exponent formatting

The final type character in a Rust format specification selects a formatting trait. For numbers, that gives you binary, octal, hexadecimal, pointer, and exponent-style representations without converting the value manually.

EXAMPLE: CI-CHECKEDTEST ASSERTED · examples/format-output/src/format_pages.rs#format-number-bases
let value = 42;
assert_eq!(format!("{value:b}"), "101010");
assert_eq!(format!("{value:o}"), "52");
assert_eq!(format!("{value:x}"), "2a");
assert_eq!(format!("{value:X}"), "2A");
assert_eq!(format!("{:e}", 42.0), "4.2e1");
Syntax Trait Example purpose
{:b} Binary base 2
{:o} Octal base 8
{:x} LowerHex lower-case base 16
{:X} UpperHex upper-case base 16
{:e} LowerExp scientific notation with e
{:E} UpperExp scientific notation with E

The suffix selects a trait, not a conversion function. Any type that implements the corresponding trait can use that syntax, including custom types.

Lower and upper hexadecimal are separate formatting traits. {:x} selects LowerHex; {:X} selects UpperHex. Scientific notation follows the same pattern with e and E.

That makes the requested representation explicit in the format string. There is no later case-conversion step hidden behind the syntax.

{:x} produces hexadecimal digits but no 0x prefix. Add the alternate flag to request the prefixed form:

{:#x}

The same pattern applies to binary and octal. See alternate formatting with # for the exact prefixes and its separate meaning for Debug.

Type suffixes can be combined with other formatting parameters. For example, hexadecimal output can have a minimum width and sign-aware zero padding. The order is defined by the format grammar, so it is better to build the specification from its parts than memorize punctuation.

Use the format specifier grammar when combining several flags at once.