Skip to content
CryoCryo home
Stdlibfmt

specification

Used by the f-string runtime · source

This file parses and renders the format spec of an f-string hole. Its parser and render helpers are internal to the standard library — the f-string runtime calls them for every hole that carries a spec — so the spec's grammar is its whole surface.

The format spec

An f-string hole may carry a spec after a colon:

spec  := [[fill]align][+][#][0][width][.precision][type]
align := '<' | '>' | '^'                (left, right, centre)
type  := 'x' | 'X' | 'o' | 'b' | 'e'    (hex lower/upper, octal, binary, scientific)
import std::fmt;

function main() -> int {
    const value: i32 = 7;
    const byte: u8 = 15;
    const ratio: f64 = 0.5;
    const label: Str = "menu";
    const delta: i32 = 42;
    const big: f64 = 1234.5;
    fmt::println(f"{value:>8}");     // right-align in a field of 8
    fmt::println(f"{byte:#04x}");    // 0x0f  - `#` adds the radix prefix, `0` zero-pads
    fmt::println(f"{ratio:.3}");     // 0.500 - three fractional digits
    fmt::println(f"{label:*^12}");   // ****menu**** - centred, padded with '*'
    fmt::println(f"{delta:+}");      // +42   - `+` signs a non-negative number too
    fmt::println(f"{big:.2e}");      // 1.23e+3
    return 0;
}
  • width is a minimum field width measured in Unicode scalars; a shorter value is padded with fill, a space by default.
  • Alignment defaults to left for text and numbers alike — chosen for predictability over a type-dependent default — and an explicit > or ^, or the 0 flag, overrides it. A 0 flag keeps the sign and any radix prefix leftmost: {-5:06} writes -00005.
  • .precision truncates a Display value to that many scalars ({"hello":.3} writes hel), or sets the fractional digits of a float. A float is rounded at the 17th place at most, past the digits an f64 carries; further places are written as zeros.
  • x, X, o and b select an integer radix, and # adds the 0x / 0o / 0b prefix. A radix formats the value's own-width two's-complement bits with no sign, so {(-5i32):x} writes fffffffb.
  • e writes a number in scientific form, with .precision digits after the mantissa's point and six without one. An integer is written as the f64 nearest it.
  • + writes the sign of a decimal number that is not negative. A radix has no sign to write, and NaN none either.
  • The spec separator is the first top-level :, so a hole that mixes a ternary with a spec parenthesises the ternary: f"{(c ? a : b):>4}".

A number in a hole with a spec is rendered on the stack; a spec on another type's Display text formats that text into a String first and pads that. The language reference covers the same grammar under f-strings.