skip to content

In a C++ std::format replacement field such as {:*>10.2f}, what do the fill, align, width, precision and type parts do?

level: middleimportance: should knowfreq 48%

answer

  1. order inside the braces matters
  2. fill needs an align after it
  3. numbers right, text left
  4. precision means digits or truncation
  5. nested braces for runtime width

basics

~20 s

After the colon, the asterisk is the fill character, > right-aligns, 10 is the minimum field width, .2 is the precision and f selects fixed-point notation, so 15.6249 becomes five asterisks then 15.62. Each part is optional, but the order is fixed.

solid answer

~40 s

The specification after the colon follows a fixed grammar: fill-and-align, sign, `#`, `0`, width, precision, `L`, type. In `{:*>10.2f}`, `*` is the **fill** (any character except a brace, and only recognised when an alignment follows it), `>` right-aligns, `10` is a **minimum** width, `.2` is the precision, and `f` asks for fixed-point. A value wider than the field is never cut. Defaults differ by type: numbers align right, strings, `char` and `bool` left. Precision means digits after the point for `f`, but the maximum number of characters for a string, and it is invalid for integers. Width and precision can come from an argument with nested braces, as in `{:>{}}`. `0` pads with zeros after the sign, unless an alignment is given.

code

cpp · 15 lines
cpp
#include <format>
#include <iostream>
#include <string>

int main() {
    std::string server = "eu-west-3";
    int players = 118;
    double tick_ms = 15.6249;

    std::cout << std::format("|{:<12}|{:>5}|{:>8.2f} ms|{:^8}|",
                             server, players, tick_ms, "OK") << '\n';
    std::cout << std::format("|{:*>10.2f}|{:+}|{:05}|{:#x}|{:08.3f}|",
                             tick_ms, players, players, 255, -tick_ms) << '\n';
    std::cout << std::format("|{:.4}|{:>{}}|{:<05}|", server, players, 7, 42) << '\n';
}

go deeper

for a junior

Recall the order fill, align, width, precision, type, and that < > ^ mean left, right and centre.

for a middle

Explain the per-type defaults and meanings: right-aligned numbers, left-aligned text, precision as digits or as truncation, zeros after the sign.

for a senior

Show runtime widths with nested fields, the shortest round-trip default for floating point, and why width never truncates a value in a table.

for a principal

Decide which specifications a team standardises for log columns and numeric output, and whether locale-specific L output is ever allowed.

## The grammar of a replacement field A replacement field is `{` optional-argument-index `:` format-spec `}`. For the standard types, the format specification follows one fixed order, and every part is optional: ``` [[fill]align][sign][#][0][width][.precision][L][type] ``` Because the order is fixed, `{:>10.2f}` is valid and `{:.2f>10}` is not. The standard calls this grammar `std-format-spec`, and it is checked at compile time against the argument's type when the format string is a literal. ## Fill and align - **align** is one of `<` (start of the field), `>` (end of the field) or `^` (centre). When centring leaves an odd amount of padding, the extra fill character goes after the value. - **fill** is any single character except `{` or `}`. It is only recognised when an alignment character follows it, so `{:*>10}` fills with `*`, while a lone `{:*10}` is not a valid specification. - With no alignment, **arithmetic types align right**, and **strings, `char` and `bool` align left**. The default fill is a space. - Width is a **minimum**: a value longer than the field is printed in full. A status line can widen but never silently lose digits. ## Sign, alternate form and zero padding - **sign** is `+` (always show a sign), `-` (only for negatives, the default) or a space (a space where a plus would go). It is valid only for arithmetic types. - `#` selects the **alternate form**. For integers it adds the base prefix (`0x`, `0b`, a leading `0` for octal); for floating point it keeps the decimal point. - `0` pads with zeros **after** the sign or base prefix: `{:08.3f}` of `-15.6249` gives `-015.625`. If an explicit alignment is present, the `0` option adds no zeros, so `{:<05}` of `42` gives `42` followed by three spaces. ## Width and precision - **width** is a positive integer, or `{}` / `{n}` to read it from an integer argument: `std::format("{:>{}}", players, 7)`. - **precision** is `.` followed by a number or by nested braces. Its meaning depends on the type: | Type of argument | What `.N` means | Example | |---|---|---| | floating point with `f` or `e` | digits after the decimal point | `{:.2f}` of 15.6249 gives `15.62` | | floating point with `g` or none | significant digits | `{:.3}` of 15.6249 gives `15.6` | | string | the longest prefix that fits N | `{:.4}` of `"eu-west-3"` gives `eu-w` | | integer | not allowed | `{:.2}` of `42` does not compile | Width is measured in **field width units**, an estimate of terminal columns: a character that a terminal displays as two columns counts as two, which keeps tables of names aligned. ## The type character 1. Integers: `d` decimal (the default), `x`/`X` hexadecimal, `o` octal, `b`/`B` binary, `c` the character with that code. 2. Floating point: `f`/`F` fixed, `e`/`E` scientific, `g`/`G` general, `a`/`A` hexadecimal. With no type and no precision, the output is the **shortest** text that reads back as the same value, so `0.1 + 0.2` prints `0.30000000000000004`. 3. Strings and `char`: `s`, and since **C++23** `?` for an escaped, quoted debug form. 4. Pointers: `p`. Only `void*`, `const void*` and `std::nullptr_t` are formattable; other pointers need a cast. `L` switches to the **locale-specific form** for arithmetic types, such as digit grouping. Without it, `std::format` ignores the locale. ## A status line, field by field ```cpp std::format("|{:<12}|{:>5}|{:>8.2f} ms|{:^8}|", server, players, tick_ms, "OK"); // |eu-west-3 | 118| 15.62 ms| OK | ``` The server name is left-aligned in 12 columns, the player count right-aligned in 5, the tick time right-aligned in 8 with two decimals, and the status centred in 8. Every column keeps its width from line to line, which is the point of a status line. ## Common slips - Putting precision on an integer: rejected, because integers have no precision. - Expecting width to truncate: it never does; use a string precision to cut text. - Writing a fill without an alignment: the fill is not recognised. - Passing a non-integer as a nested width: rejected, because a dynamic width must come from an integer argument. - Reaching for iostream habits: there is no sticky state in `std::format`. Each field carries its own specification, so a precision set for one value never leaks into the next line the way `std::setprecision` stays on a stream.

  • How do you print a number with a width chosen at run time?
    Use a nested replacement field for the width: `std::format("{:>{}}", value, width)`. The inner `{}` consumes the next argument, which must have an integer type; a negative value throws `std::format_error`. Precision works the same way, as in `{:.{}f}`. With manual indexing you write `{0:>{1}}`.
  • Why does {:<05} of 42 print 42 and three spaces rather than 00042?
    The `0` option pads with zeros only when no alignment is given. With an explicit `<`, `>` or `^`, the standard sets the number of zeros to insert to zero, and ordinary fill characters (spaces by default) do the padding instead.

  • A value wider than the field width is truncated to fit
  • Every type aligns right by default, strings included
  • Precision on an integer sets the minimum number of digits
  • The fill character works without an alignment character after it
  • std::format applies the global locale's digit grouping by default

Assumes C++20 std::format; the ? debug type for strings and characters was added in C++23.