Programming Search⌘K

Conceptcore

Format specifiers

Also called format specifier, format string, conversion specification, printf format, format spec, format_spec, format mini-language, field width, precision, alignment, verbs, %d, %s, %5.2f, {:>8}, composite formatting.

A format specifier is a short code in a format string, such as %5.2f or {:>8}, that tells a format function how to show one value: its width, alignment, precision, sign and base.

Applies to
core-languages

Idea

A format function takes a format string and a list of values. The format string is text with codes in it, and each code tells the function how to show one value. In C, "The format string consists of ordinary byte characters (except %), which are copied unchanged into the output stream, and conversion specifications"1. A conversion specification starts with % and ends with a letter for the type:

#include <stdio.h>

int main(void) {
    printf("[%d] [%5d] [%-5d] [%05d]\n", 42, 42, 42, 42);
    printf("[%f] [%.2f] [%8.3f] [%+.1f]\n", 3.14159, 3.14159, 3.14159, 3.14159);
    printf("[%s] [%6s] [%-6s] [%.2s]\n", "abc", "abc", "abc", "abc");
    printf("[%x] [%#o] [%e] [%%]\n", 255, 8, 12345.678);
    return 0;
}
Output
[42] [   42] [42   ] [00042]
[3.141590] [3.14] [   3.142] [+3.1]
[abc] [   abc] [abc   ] [ab]
[ff] [010] [1.234568e+04] [%]

%5d is an integer in a field of 5 characters, %-5d is the same on the left, and %05d fills with zeros. %.2f is a float with 2 digits after the point, and %8.3f adds a width of 8. For a string, the precision %.2s is the largest number of characters. %% gives one %.

How it works

The parts of a specifier. Most specifiers have the same parts, in this order: flags, a width, a precision and a type. In C, "(optional) integer value or *: specifies minimum field width. The result is padded with space characters (by default), if required, on the left when right-justified, or on the right if left-justified"1. The precision is "(optional) . followed by non-negative integer number or *"1: the number of digits after the point for a float, the smallest number of digits for an integer, and the largest number of characters for a string.

Two families. The format strings of today come in two families.

  • The printf family uses % and a type letter: C, C++ printf, Java, Go, Bash printf and PHP. Java's syntax is %[argument_index$][flags][width][.precision]conversion2, and "Formatted printing for the Java language is heavily inspired by C's printf"2. Go's package fmt says: "The format 'verbs' are derived from C's but are simpler"3.
  • The brace family uses {} with an optional index or name and a specifier after :: Python, Rust and C++ std::format. Python's general form has the options fill, align, sign, z, # and 0, then a width, a grouping, a precision and a type4. Rust has format_spec := [[fill]align][sign]['#']['0'][width]['.' precision][type]5, and for C++ std::format, "the format specification is based on the format specification in Python"6.

.NET is a third form: a format item is {index[,width][:formatString]}7, and the format string after the colon is a letter and a precision, such as F2 or N0. "A standard numeric format string takes the form [format specifier][precision specifier]"8.

The same field in each family. The table shows one field, a float in 8 characters with 2 decimals:

Meaning C, Java, Go Python, Rust, C++ std::format C#
right-aligned, width 8, 2 decimals %8.2f {:8.2f} (Rust: {:8.2}) {0,8:F2}
left-aligned %-8.2f {:<8.2f} {0,-8:F2}
zero fill %08.2f {:08.2f} {0:00000.00}
plus sign %+.2f {:+.2f} {0:+0.00;-0.00}
hexadecimal %x {:x} {0:x}
any fill, centered none {:*^8} none

In the brace family, a number is right-aligned and a string is left-aligned by default, and any character can be the fill. In Python, , and _ group digits: "',' Inserts a comma every 3 digits for integer presentation type 'd' and floating-point presentation types"4.

Default formats. A placeholder with no specifier uses the default text of the value. "A general convention is that an empty format specification produces the same result as if you had called str() on the value"4. Go's %v is "the value in a default format"3, and {} in Rust and C++ is the default form.

Arguments by position. A format string can pick its arguments by number, so one value can appear twice, or a translation can change the order. Rust says that if the index is omitted, "it is assumed to be “the next argument”"5. Java uses %1$s, Go uses %[1]s, and Python, Rust and C++ use {0}.

In languages

LanguageVerdictNote
PythonNative
C++Standard library
JavaStandard library
CStandard library
C#Standard library
JavaScriptAbsent
TypeScriptAbsentTypeScript has no format strings, as JavaScript. A program uses toFixed, padStart and Intl.NumberFormat. No example file exists.
GoStandard library
RustNative
KotlinStandard libraryKotlin calls java.util.Formatter through String.format and the extension function format, so the specifiers are those of Java. No example file exists because kotlinc is not installed.
SQLIdiomStandard SQL has no format strings. Databases add functions such as to_char in PostgreSQL and Oracle, FORMAT in SQL Server and MySQL, and printf in SQLite. No example file exists.
BashNativeThe Bash builtin printf takes the conversion specifications of C, such as %5d, %-8s and %.2f, and repeats the format when more arguments remain. No example file exists.
PowerShellNativeThe PowerShell operator -f takes .NET format items, such as "{0,8:F2}" -f $x, and the method ToString takes a .NET format string. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML shows text and has no format codes for values.
CSSDoes not applyCSS does not format numbers. The list-style-type of a counter, such as decimal-leading-zero or lower-roman, is the closest feature.
Regular expressionsDoes not applyA regular expression matches text and does not format values.
Language Verdict Mechanism
Python native the format mini-language in f-strings, str.format and format, and the older % operator
JavaScript absent no format strings; toFixed, padStart, toString(16) and Intl.NumberFormat
TypeScript absent as in JavaScript
Java stdlib java.util.Formatter, through String.format, formatted and printf
Kotlin stdlib String.format and "...".format(...) from Java
C# stdlib composite formatting {0,8:F2}, in string.Format, Console.WriteLine and $"..."
Go stdlib the package fmt, with verbs such as %v, %d and %8.2f
Rust native the macros format! and println!, checked at compile time
C stdlib printf, snprintf and the other functions of <stdio.h>
C++ stdlib std::format and std::print with the brace syntax, and printf from C
Bash native the builtin printf, with the specifiers of C
PowerShell native the operator -f, with the .NET format items: "{0,8:F2}" -f $x
SQL idiom no standard format strings; functions such as to_char, FORMAT or printf in some databases
Regex n/a patterns match text and do not format values
HTML n/a HTML shows text and does not format values
CSS n/a CSS does not format numbers; counters have styles such as decimal-leading-zero

C and Bash. C trusts the format string: "If any argument after default argument promotions is not the type expected by the corresponding conversion specification"1, "the behavior is undefined"1. Compilers warn when the format string is a literal. The Bash builtin printf uses the same specifiers and repeats the format if there are more values.

Java and Go. Both check the types at run time. "Java formatting is more strict than C's; for example, if a conversion is incompatible with a flag, an exception will be thrown"2. Go puts the error into the output: "If an invalid argument is given for a verb, such as providing a string to %d, the generated string will contain a description of the problem"3, for example %!d(string=hi).

Rust and C++. The format string must be a literal, so the compiler checks it against the types of the values. In Rust, "A format string is required to use all of its arguments, otherwise it is a compile-time error"5.

PythonGitHub
x = 3.14159
n = 1234567

print(f"[{x:8.2f}] [{x:<8.2f}] [{x:08.2f}] [{x:+.1f}]")
print(f"[{'abc':>6}] [{'abc':*^9}] [{n:,}] [{n:_}]")
print(f"[{255:x}] [{255:#06x}] [{255:b}] [{0.25:.0%}] [{n:.3e}]")
print("{0} {1} {0}".format("a", "b"), format(x, ".3f"))
print("%5d|%-5s|%.2f" % (42, "ab", x))
Output
[    3.14] [3.14    ] [00003.14] [+3.1]
[   abc] [***abc***] [1,234,567] [1_234_567]
[ff] [0x00ff] [11111111] [25%] [1.235e+06]
a b a 3.142
   42|ab   |3.14
  • Verdict: native. The format mini-language works in f-strings, in str.format and in the function format. It has fill and alignment with <, > and ^, a sign, # for the base prefix, zero fill, a width, , or _ for digit groups, a precision and a type. The older operator % uses the C specifiers.
#include <cstdio>
#include <format>
#include <iostream>

int main() {
    double x = 3.14159;
    std::cout << std::format("[{:8.2f}] [{:<8.2f}] [{:08.2f}] [{:+.1f}]\n", x, x, x, x);
    std::cout << std::format("[{:>6}] [{:*^9}] [{:x}] [{:#06x}] [{:b}]\n", "abc", "abc", 255, 255, 5);
    std::cout << std::format("[{1}-{0}-{1}] [{2:e}]\n", "a", "b", 1234.5);
    std::printf("[%8.2f] [%-6s] [%05d]\n", x, "abc", 42);
}
Output
[    3.14] [3.14    ] [00003.14] [+3.1]
[   abc] [***abc***] [ff] [0x00ff] [101]
[b-a-b] [1.234500e+03]
[    3.14] [abc   ] [00042]
  • Verdict: stdlib. std::format takes the brace syntax of Python, and the compiler checks a literal format string against the types. C++ keeps printf from C as well.
JavaGitHub
import java.util.IllegalFormatException;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        double x = 3.14159;
        Locale l = Locale.ROOT;
        System.out.println(String.format(l, "[%8.2f] [%-8.2f] [%08.2f] [%+.1f]", x, x, x, x));
        System.out.println(String.format(l, "[%6s] [%-6s] [%,d] [%x] [%#o]", "abc", "abc", 1234567, 255, 8));
        System.out.println(String.format(l, "%2$s %1$s %2$s", "a", "b"));
        try {
            String.format(l, "%d", "three");
        } catch (IllegalFormatException e) {
            System.out.println(e.getClass().getSimpleName());
        }
    }
}
Output
[    3.14] [3.14    ] [00003.14] [+3.1]
[   abc] [abc   ] [1,234,567] [ff] [010]
b a b
IllegalFormatConversionException
  • Verdict: stdlib. java.util.Formatter reads the specifiers of C, plus %,d for digit groups and %2$s for an argument by position. A wrong type throws a subclass of IllegalFormatException at run time. The formats use the default locale, so the program passes Locale.ROOT.
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>

int main(void) {
    double x = 3.14159;
    int width = 8, precision = 2;
    printf("[%*.*f] [%-*s]\n", width, precision, x, 6, "abc");

    size_t n = strlen("hello");
    long long big = 9000000000LL;
    int64_t id = INT64_C(-42);
    printf("%zu %lld %" PRId64 "\n", n, big, id);

    char buf[16];
    int len = snprintf(buf, sizeof buf, "%08.3f", x);
    printf("%s %d\n", buf, len);
    return 0;
}
Output
[    3.14] [abc   ]
5 9000000000 -42
0003.142 8
  • Verdict: stdlib. printf and snprintf in <stdio.h> read the conversion specifications. * takes the width or the precision from an argument. The length modifiers must match the type: %zu for size_t, %lld for long long, and the macros of <inttypes.h>, such as PRId64, for the fixed-width types. A wrong type is undefined behavior.
using System;
using System.Globalization;

CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
double x = 3.14159;
Console.WriteLine("[{0,8:F2}] [{0,-8:F2}] [{0:00000.00}] [{0:+0.0;-0.0}]", x);
Console.WriteLine("[{0,6}] [{0,-6}] [{1:N0}] [{2:X}] [{2:X4}]", "abc", 1234567, 255);
Console.WriteLine("[{0:E2}] [{1:P0}] [{2:D5}]", 1234.5, 0.25, 42);
Console.WriteLine($"[{x,8:F2}] [{{x}}]");
Output
[    3.14] [3.14    ] [00003.14] [+3.1]
[   abc] [abc   ] [1,234,567] [FF] [00FF]
[1.23E+003] [25 %] [00042]
[    3.14] [{x}]
  • Verdict: stdlib. A format item is {index,width:format}. A negative width aligns on the left. The format is a standard string such as F2, N0, X4, E2, P0 or D5, or a custom pattern such as 00000.00. The output depends on the current culture, so the program sets the invariant culture. Interpolated strings use the same items.
JavaScriptGitHub
const x = 3.14159;
console.log(`[${x.toFixed(2).padStart(8)}] [${x.toFixed(2).padEnd(8)}] [${x.toFixed(2).padStart(8, "0")}]`);
console.log(`[${(255).toString(16)}] [${(5).toString(2)}] [${(1234.5).toExponential(2)}] [${(1234.5).toPrecision(2)}]`);
console.log(new Intl.NumberFormat("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(1234567.891));
Output
[    3.14] [3.14    ] [00003.14]
[ff] [101] [1.23e+3] [1.2e+3]
1,234,567.89
  • Verdict: absent. JavaScript has no format strings. Each part of a format is a method: toFixed for the decimals, toExponential and toPrecision, toString(16) for a base, padStart and padEnd for the width, and Intl.NumberFormat for digit groups.
package main

import "fmt"

type point struct{ X, Y int }

func main() {
	x := 3.14159
	fmt.Printf("[%8.2f] [%-8.2f] [%08.2f] [%+.1f]\n", x, x, x, x)
	fmt.Printf("[%6s] [%-6s] [%q] [%x] [%#o]\n", "abc", "abc", "abc", 255, 8)
	p := point{1, 2}
	fmt.Printf("%v %+v %#v %T\n", p, p, p, p)
	fmt.Printf("%[2]s %[1]s %[2]s\n", "a", "b")
}
Output
[    3.14] [3.14    ] [00003.14] [+3.1]
[   abc] [abc   ] ["abc"] [ff] [010]
{1 2} {X:1 Y:2} main.point{X:1, Y:2} main.point
b a b
  • Verdict: stdlib. The package fmt has the flags, widths and precisions of C, and verbs of its own: %v for the default format of any value, %+v with field names, %#v in Go syntax, %T for the type and %q for a quoted string. %[2]s picks an argument by position.
RustGitHub
fn main() {
    let x = 3.14159_f64;
    println!("[{x:8.2}] [{x:<8.2}] [{x:08.2}] [{x:+.1}]");
    println!("[{:>6}] [{:*^9}] [{:x}] [{:#06x}] [{:b}]", "abc", "abc", 255, 255, 5);
    println!("[{:e}] [{:?}] [{:?}]", 1234.5, "a\"b", (1, 2.0));
    let w = 7;
    let p = 3;
    println!("[{x:w$.p$}] [{0}-{1}-{0}]", "a", "b");
}
Output
[    3.14] [3.14    ] [00003.14] [+3.1]
[   abc] [***abc***] [ff] [0x00ff] [101]
[1.2345e3] ["a\"b"] [(1, 2.0)]
[  3.142] [a-b-a]
  • Verdict: native. The macros format! and println! take a format string in the brace syntax, with fill, alignment, sign, #, zero fill, width and precision. The type letter picks a trait: none for Display, ? for Debug, x and b for hexadecimal and binary. w$ and p$ read the width and the precision from variables. The compiler checks the whole format string.
  • Interpolation with a specifier. f"{price:.2f}", $"{price:F2}" and format!("{price:.2}") put the specifier inside the interpolated string. See String interpolation.
  • Locale. A specifier can use the decimal separator and the digit groups of a locale: %'d in POSIX printf, the type n in Python, L in C++ and N in .NET. See Locale-aware formatting.
  • Custom formats. A type can define its own specifiers: __format__ in Python, IFormattable in .NET, std::formatter in C++ and the traits of std::fmt in Rust. Dates have their own codes, such as %Y-%m-%d.
  • Scanning. scanf and fmt.Sscanf use the same specifiers to read values from text.

Pitfalls

  • A format string from a user. If a program passes outside text as the format string, the text can contain specifiers. "the format string can be the value of a variable, which allows for dynamic formatting but also a security vulnerability known as an uncontrolled format string exploit"9. In C, %n writes to memory, so this is a serious weakness. Write printf("%s", text), not printf(text).
  • The wrong type. In C, %d with a long long or %f with an int is undefined behavior. Use %lld, %zu for size_t, and the macros of <inttypes.h> for the fixed-width types. Java throws an exception, and Go prints a description of the error:

This code runs but gives a wrong answer on purpose.

package main

import "fmt"

func main() {
	fmt.Printf("%d items\n", "three")
	fmt.Printf("%d and %d\n", 1)
	fmt.Printf("%.2f\n", 3)
}
Output
%!d(string=three) items
1 and %!d(MISSING)
%!f(int=03)

go vet reports these calls before the program runs.

  • Width is a minimum. A width never cuts a value. %3d of 12345 gives 12345, so a table column moves when a value is long. A precision cuts a string, but not a number.
  • Width counts characters, not columns. A width counts bytes in C and Bash, UTF-16 units in Java and C#, and code points in Python and Rust. A wide character such as a Chinese ideograph takes two columns on a terminal, so a padded table can still look wrong. See Pad a string.
  • Rounding. %.2f rounds the binary value of the float, not the decimal number in the source. 2.675 is a little less than 2.675 in binary, so C and Python show 2.67. See Format a number with fixed decimals.
  • A literal brace or percent sign. In the printf family, write %%. In the brace family, write {{ and }}.

Cost

A format function parses the format string each time it runs, unless the compiler does the work: format! in Rust, std::format with a literal in C++, and interpolated strings in C# are parsed at compile time. The conversion of each value costs much more than the parse, in particular for floats, where the shortest correct digits need a special algorithm. For a hot loop, a format string that does not change is cheap, and a new string for each line is the main cost.

History

The printf family is old. "In 1967, BCPL appeared"9, and its library had the routine writef, which acted as a function call. "In 1973, printf was included as a C standard library routine as part of Version 4 Unix"9. "In 1990, the printf command-line program, modeled after the C standard library function, was included with 4.3BSD-Reno"9. "In 2004, Java 5.0 (1.5) released, which extended the class java.io.PrintStream, adding a method named printf()"9. Python added str.format with its brace syntax, and C++ took that syntax for std::format6.

References

  1. printf, fprintf, sprintf, snprintf, C reference, cppreference.com, Parameters; conversion specification
  2. Class Formatter, Java SE 25 API, Format String Syntax
  3. Package fmt, The Go Standard Library, Printing; Format errors
  4. string, Common string operations, Python documentation, Format Specification Mini-Language
  5. Module std::fmt, The Rust Standard Library, Positional parameters; Syntax
  6. Standard format specification, C++ reference, cppreference.com, Introduction
  7. Composite formatting, .NET documentation, Format item syntax
  8. Standard numeric format strings, .NET documentation, Introduction
  9. printf, Wikipedia, History; Uncontrolled format string exploit

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/3SSY7M/text.yaml