std.format

This package provides string formatting functionality using printf style format strings.

Limitation: This package does not support localization, but adheres to the rounding mode of the floating point unit, if available.

Format Strings

The functions contained in this package use format strings. A format string describes the layout of another string for reading or writing purposes. A format string is composed of normal text interspersed with format specifiers. A format specifier starts with a percentage sign '%', optionally followed by one or more

parameters and ends with a format indicator. A format

indicator may be a simple format character or a compound indicator.

Format strings are composed according to the following grammar: FormatStringItem FormatString FormatStringItem: Character FormatSpecifier FormatSpecifier: '%' Parameters FormatIndicator FormatIndicator: FormatCharacter CompoundIndicator FormatCharacter: see remark below CompoundIndicator: '(' FormatString '%)' '(' FormatString '%|' Delimiter '%)' Delimiter empty Character Delimiter Parameters: Position Flags Width Precision Separator Position: empty Integer '$' Integer ':' Integer '$' Integer ':' '$' Flags: empty Flag Flags Flag: '-'|'+'|' '|'0'|'#'|'=' Width: OptionalPositionalInteger Precision: empty '.' OptionalPositionalInteger Separator: empty ',' OptionalInteger ',' OptionalInteger '?' OptionalInteger: empty Integer '*' OptionalPositionalInteger: OptionalInteger '*' Integer '$' Character '%%' AnyCharacterExceptPercent Integer: NonZeroDigit Digits Digits: empty Digit Digits NonZeroDigit: '1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9' Digit: '0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9'

Note

FormatCharacter is unspecified. It can be any character

that has no other purpose in this grammar, but it is recommended to assign (lower- and uppercase) letters.

Note: The Parameters of a CompoundIndicator are currently limited to a '-' flag.

Format Indicator

The format indicator can either be a single character or an expression surrounded by '%(' and '%)'. It specifies the basic manner in which a value will be formatted and is the minimum requirement to format a value.

The following characters can be used as format characters:

The compound indicator can be used to describe compound types like arrays or structs in more detail. A compound type is enclosed within '%(' and '%)'. The enclosed sub-format string is applied to individual elements. The trailing portion of the sub-format string following the specifier for the element is interpreted as the delimiter, and is therefore omitted following the last element. The '%|' specifier may be used to explicitly indicate the start of the delimiter, so that the preceding portion of the string will be included following the last element.

The format string inside of the compound indicator should contain exactly one format specifier (two in case of associative arrays), which specifies the formatting mode of the elements of the compound type. This format specifier can be a compound indicator itself.

Note: Inside a compound indicator, strings and characters are escaped automatically. To avoid this behavior, use "%-(" instead of "%(".

Flags

There are several flags that affect the outcome of the formatting.

Width, Precision and Separator

The width parameter specifies the minimum width of the result.

The meaning of precision depends on the format indicator. For integers it denotes the minimum number of digits printed, for real numbers it denotes the number of fractional digits and for strings and compound types it denotes the maximum number of elements that are included in the output.

A separator is used for formatting numbers. If it is specified, the output is divided into chunks of three digits, separated by a ','. The number of digits in a chunk can be given explicitly by providing a number or a '*' after the ','.

In all three cases the number of digits can be replaced by a '*'. In this scenario, the next argument is used as the number of digits. If the argument is a negative number, the precision and

separator parameters are considered unspecified. For width,

the absolute value is used and the '-' flag is set.

The separator can also be followed by a '?'. In that case, an additional argument is used to specify the symbol that should be used to separate the chunks.

Position

By default, the arguments are processed in the provided order. With the position parameter it is possible to address arguments directly. It is also possible to denote a series of arguments with two numbers separated by ':', that are all processed in the same way. The second number can be omitted. In that case the series ends with the last argument.

It's also possible to use positional arguments for width, precision and separator by adding a number and a '$' after the '*'.

Types

This section describes the result of combining types with format characters. It is organized in 2 subsections: a list of general information regarding the formatting of types in the presence of format characters and a table that contains details for every available combination of type and format character.

When formatting types, the following rules apply:

  • If the format character is upper case, the resulting string will

    be formatted using upper case letters.

  • The default precision for floating point numbers is 6 digits.
  • Rounding of floating point numbers adheres to the rounding mode

    of the floating point unit, if available.

  • The floating point values NaN and Infinity are formatted as

    nan and inf, possibly preceded by '+' or '-' sign.

  • Formatting reals is only supported for 64 bit reals and 80 bit reals.

    All other reals are cast to double before they are formatted. This will cause the result to be inf for very large numbers.

  • Characters and strings formatted with the 's' format character

    inside of compound types are surrounded by single and double quotes and unprintable characters are escaped. To avoid this, a '-' flag can be specified for the compound specifier (e.g. "%-(%s%)" instead of "%(%s%)" ).

  • Structs, unions, classes and interfaces are formatted by calling a

    toString method if available. See module std.format.write for more details.

  • Only part of these combinations can be used for reading. See module std.format.read for more

    detailed information.

This table contains descriptions for every possible combination of type and format character:

Types 3

classFormatException : Exception

Signals an issue encountered while formatting.

Constructors
this()Generic constructor.
this(string msg, string fn = __FILE__, size_t ln = __LINE__, Throwable next = null)Creates a new instance of `FormatException`.
aliasenforceFmt = enforce!FormatException
structNoOpSink
Methods
void put(E)(scope const E) pure @safe @nogc nothrow

Functions 9

fnvoid formatElement(Writer, T, Char)(auto ref Writer w, T val, scope const ref FormatSpec!Char f) if (is(StringTypeOf!T) && !hasToString!(T, Char) && !is(T == enum))
deprecated formatElement was accidentally made public and will be removed in 2.107.0
fnvoid formatElement(Writer, T, Char)(auto ref Writer w, T val, scope const ref FormatSpec!Char f) if (is(CharTypeOf!T) && !is(T == enum))
deprecated formatElement was accidentally made public and will be removed in 2.107.0
fnvoid formatElement(Writer, T, Char)(auto ref Writer w, auto ref T val, scope const ref FormatSpec!Char f) if ((!is(StringTypeOf!T) || hasToString!(T, Char)) && !is(CharTypeOf!T) || is(T == enum))
deprecated formatElement was accidentally made public and will be removed in 2.107.0
fnT unformatElement(T, Range, Char)(ref Range input, scope const ref FormatSpec!Char spec) if (isInputRange!Range)
deprecated unformatElement was accidentally made public and will be removed in 2.107.0
fnimmutable(Char)[] format(Char, Args...)(in Char[] fmt, Args args) if (isSomeChar!Char)Converts its arguments according to a format string into a string.
fntypeof(fmt) format(alias fmt, Args...)(Args args) if (isSomeString!(typeof(fmt)))ditto
private fnsize_t guessLength(Char, S)(S fmtString)
fnchar[] sformat(Char, Args...)(return scope char[] buf, scope const(Char)[] fmt, Args args)Converts its arguments according to a format string into a buffer. The buffer has to be large enough to hold the formatted string.
fnchar[] sformat(alias fmt, Args...)(char[] buf, Args args) if (isSomeString!(typeof(fmt)))ditto