| Submodule | Function Name | Description |
|---|---|---|
| package | format | Converts its arguments according to a format string into a string. |
| package | sformat | Converts its arguments according to a format string into a buffer. |
| package | FormatException | Signals a problem while formatting. |
| write | formattedWrite | Converts its arguments according to a format string and writes the result to an output range. |
| write | formatValue | Formats a value of any type according to a format specifier and writes the result to an output range. |
| read | formattedRead | Reads an input range according to a format string and stores the read values into its arguments. |
| read | unformatValue | Reads a value from the given input range and converts it according to a format specifier. |
| spec | FormatSpec | A general handler for format strings. |
| spec | singleSpec | Helper function that returns aFormatSpec for a single format specifier. |
LimitationThis package does not support localization, but adheres to the rounding mode of the floating point unit, if available.
FormatString:FormatStringItemFormatStringFormatStringItem:CharacterFormatSpecifierFormatSpecifier:'%'ParametersFormatIndicatorFormatIndicator:FormatCharacterCompoundIndicatorFormatCharacter:see remark belowCompoundIndicator:'('FormatString'%)''('FormatString'%|'Delimiter'%)'DelimiteremptyCharacterDelimiterParameters:PositionFlagsWidthPrecisionSeparatorPosition:emptyInteger'$'Integer':'Integer'$'Integer':''$'Flags:emptyFlagFlagsFlag:'-'|'+'|' '|'0'|'#'|'='Width:OptionalPositionalIntegerPrecision:empty'.'OptionalPositionalIntegerSeparator:empty','OptionalInteger','OptionalInteger'?'OptionalInteger:emptyInteger'*'OptionalPositionalInteger:OptionalInteger'*'Integer'$'Character'%%'AnyCharacterExceptPercentInteger:NonZeroDigitDigitsDigits:emptyDigitDigitsNonZeroDigit:'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9'Digit:'0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9'NoteFormatCharacter is unspecified. It can be any characterthat has no other purpose in this grammar, but it isrecommended to assign (lower- and uppercase) letters.
NoteTheParameters of aCompoundIndicator are currentlylimited to a'-' flag.
| FormatCharacter | Semantics |
|---|---|
| 's' | To be formatted in a human readable format. Can be used with all types. |
| 'c' | To be formatted as a character. |
| 'd' | To be formatted as a signed decimal integer. |
| 'u' | To be formatted as a decimal image of the underlying bit representation. |
| 'b' | To be formatted as a binary image of the underlying bit representation. |
| 'o' | To be formatted as an octal image of the underlying bit representation. |
| 'x' /'X' | To be formatted as a hexadecimal image of the underlying bit representation. |
| 'e' /'E' | To be formatted as a real number in decimal scientific notation. |
| 'f' /'F' | To be formatted as a real number in decimal natural notation. |
| 'g' /'G' | To be formatted as a real number in decimal short notation. Depending on the number, a scientific notation or a natural notation is used. |
| 'a' /'A' | To be formatted as a real number in hexadecimal scientific notation. |
| 'r' | To be formatted as raw bytes. The output may not be printable and depends on endianness. |
NoteInside acompound indicator, strings and characters areescaped automatically. To avoid this behavior, use"%-("instead of"%(".
| Flag | Semantics |
|---|---|
| '-' | When the formatted result is shorter than the value given by the width parameter, the output is left justified. Without the'-' flag, the output remains right justified. There are two exceptions where the'-' flag has a different meaning: (1) with'r' it denotes to use little endian and (2) in case of a compound indicator it means that no special handling of the members is applied. |
| '=' | When the formatted result is shorter than the value given by the width parameter, the output is centered. If the central position is not possible it is moved slightly to the right. In this case, if'-' flag is present in addition to the'=' flag, it is moved slightly to the left. |
| '+' / ' ' | Applies to numerical values. By default, positive numbers are not formatted to include the+ sign. With one of these two flags present, positive numbers are preceded by a plus sign or a space. When both flags are present, a plus sign is used. In case of'r', a big endian format is used. |
| '0' | Is applied to numerical values that are printed right justified. If the zero flag is present, the space left to the number is filled with zeros instead of spaces. |
| '#' | Denotes that an alternative output must be used. This depends on the type to be formatted and theformat character used. See the sections below for more information. |
| Type | Format Character | Formatted as... |
|---|---|---|
| null | 's' | null |
| bool | 's' | false ortrue |
| 'b','d','o','u','x','X' | As the integrals 0 or 1 with the same format character.Please note, that'o' and'x' with'#' flag might produce unexpected results due to special handling of the value 0. | |
| 'r' | \0 or\1 | |
| Integral | 's','d' | A signed decimal number. The'#' flag is ignored. |
| 'b','o','u','x','X' | An unsigned binary, decimal, octal or hexadecimal number. In case of'o' and'x', the'#' flag denotes that the number must be preceded by0 and0x, with the exception of the value 0, where this does not apply. For'b' and'u' the'#' flag has no effect. | |
| 'e','E','f','F','g','G','a','A' | As a floating point value with the same specifier. Default precision is large enough to add all digits of the integral value. In case of'a' and'A', the integral digit can be any hexadecimal digit. | |
| 'r' | Characters taken directly from the binary representation. | |
| Floating Point | 'e','E' | Scientific notation: Exactly one integral digit followed by a dot and fractional digits, followed by the exponent. The exponent is formatted as'e' followed by a'+' or'-' sign, followed by at least two digits. When there are no fractional digits and the'#' flag isnot present, the dot is omitted. |
| 'f','F' | Natural notation: Integral digits followed by a dot and fractional digits. When there are no fractional digits and the'#' flag isnot present, the dot is omitted.Please note: the difference between'f' and'F' is only visible forNaN andInfinity. | |
| 's','g','G' | Short notation: If the absolute value is larger than10 ^^ precision or smaller than0.0001, the scientific notation is used. If not, the natural notation is applied. In both casesprecision denotes the count of all digits, including the integral digits. Trailing zeros (including a trailing dot) are removed. If'#' flag is present, trailing zeros are not removed. | |
| 'a','A' | Hexadecimal scientific notation:0x followed by1 (or0 in case of value zero or denormalized number) followed by a dot, fractional digits in hexadecimal notation and an exponent. The exponent is build byp, followed by a sign and the exponent indecimal notation. When there are no fractional digits and the'#' flag isnot present, the dot is omitted. | |
| 'r' | Characters taken directly from the binary representation. | |
| Character | 's','c' | As the character. Inside of a compound indicator's' is treated differently: The character is surrounded by single quotes and non printable characters are escaped. This can be avoided by preceding the compound indicator with a'-' flag (e.g."%-(%s%)"). |
| 'b','d','o','u','x','X' | As the integral that represents the character. | |
| 'r' | Characters taken directly from the binary representation. | |
| String | 's' | The sequence of characters that form the string. Inside of a compound indicator the string is surrounded by double quotes and non printable characters are escaped. This can be avoided by preceding the compound indicator with a'-' flag (e.g."%-(%s%)"). |
| 'r' | The sequence of characters, each formatted with'r'. | |
| compound | As an array of characters. | |
| Array | 's' | When the elements are characters, the array is formatted as a string. In all other cases the array is surrounded by square brackets and the elements are separated by a comma and a space. If the elements are strings, they are surrounded by double quotes and non printable characters are escaped. |
| 'r' | The sequence of the elements, each formatted with'r'. | |
| compound | The sequence of the elements, each formatted according to the specifications given inside of the compound specifier. | |
| Associative Array | 's' | As a sequence of the elements in unpredictable order. The output is surrounded by square brackets. The elements are separated by a comma and a space. The elements are formatted askey:value. |
| compound | As a sequence of the elements in unpredictable order. Each element is formatted according to the specifications given inside of the compound specifier. The first specifier is used for formatting the key and the second specifier is used for formatting the value. The order can be changed with positional arguments. For example"%(%2$s (%1$s), %)" will write the value, followed by the key in parenthesis. | |
| Enum | 's' | The name of the value. If the name is not available, the base value is used, preceeded by a cast. |
| All, but's' | Enums can be formatted with all format characters that can be used with the base value. In that case they are formatted like the base value. | |
| Input Range | 's' | When the elements of the range are characters, they are written like a string. In all other cases, the elements are enclosed by square brackets and separated by a comma and a space. |
| 'r' | The sequence of the elements, each formatted with'r'. | |
| compound | The sequence of the elements, each formatted according to the specifications given inside of the compound specifier. | |
| Struct | 's' | When the struct has neither an applicabletoString nor is an input range, it is formatted as follows:StructType(field1, field2, ...). |
| Class | 's' | When the class has neither an applicabletoString nor is an input range, it is formatted as the fully qualified name of the class. |
| Union | 's' | When the union has neither an applicabletoString nor is an input range, it is formatted as its base name. |
| Pointer | 's' | A null pointer is formatted as 'null'. All other pointers are formatted as hexadecimal numbers with the format character'X'. |
| 'x','X' | Formatted as a hexadecimal number. | |
| SIMD vector | 's' | The array is surrounded by square brackets and the elements are separated by a comma and a space. |
| 'r' | The sequence of the elements, each formatted with'r'. | |
| compound | The sequence of the elements, each formatted according to the specifications given inside of the compound specifier. | |
| Delegate | 's','r', compound | As the.stringof of this delegate treated as a string.Please note: The implementation is currently buggy and its use is discouraged. |
Sourcestd/format/package.d
// Easiest way is to use `%s` everywhere:// "I got 30 eggs for 5.27 euros."writeln(format("I got %s %s for %s euros.", 30,"eggs", 5.27));// Other format characters provide more control:// "I got 11110 65676773 for 5.270000 euros."writeln(format("I got %b %(%X%) for %f euros.", 30,"eggs", 5.27));
/*The trailing end of the sub-format string following the specifier foreach item is interpreted as the array delimiter, and is thereforeomitted following the last array item: */ writeln(format("My items are %(%s %).", [1, 2, 3]));// "My items are 1 2 3." writeln(format("My items are %(%s, %).", [1, 2, 3]));// "My items are 1, 2, 3."/*The "%|" delimiter specifier may be used to indicate where thedelimiter begins, so that the portion of the format string prior toit will be retained in the last array element: */ writeln(format("My items are %(-%s-%|, %).", [1, 2, 3]));// "My items are -1-, -2-, -3-."/*These compound format specifiers may be nested in the case of anested array argument: */auto mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];assert(format("%(%(%d %) - %)", mat),"1 2 3 - 4 5 6 - 7 8 9");assert(format("[%(%(%d %) - %)]", mat),"[1 2 3 - 4 5 6 - 7 8 9]");assert(format("[%([%(%d %)]%| - %)]", mat),"[1 2 3] - [4 5 6] - [7 8 9]");/*Strings and characters are escaped automatically inside compoundformat specifiers. To avoid this behavior, use "%-(" instead of "%(": */// `My friends are ["John", "Nancy"].` writeln(format("My friends are %s.", ["John","Nancy"]));// `My friends are "John", "Nancy".` writeln(format("My friends are %(%s, %).", ["John","Nancy"]));// `My friends are John, Nancy.` writeln(format("My friends are %-(%s, %).", ["John","Nancy"]));
// Flags can be used to influence to outcome:writeln(format("%g != %+#g", 3.14, 3.14));// "3.14 != +3.14000"// Width and precision help to arrange the formatted result:writeln(format(">%10.2f<", 1234.56789));// "> 1234.57<"// Numbers can be grouped:writeln(format("%,4d",int.max));// "21,4748,3647"// It's possible to specify the position of an argument:writeln(format("%3$s %1$s", 3, 17, 5));// "5 3"
// Width as argumentwriteln(format(">%*s<", 10,"abc"));// "> abc<"// Precision as argumentwriteln(format(">%.*f<", 5, 123.2));// ">123.20000<"// Grouping as argumentwriteln(format("%,*d", 1,int.max));// "2,1,4,7,4,8,3,6,4,7"// Grouping separator as argumentwriteln(format("%,3?d", '_',int.max));// "2_147_483_647"// All at oncewriteln(format("%*.*,*?d", 20, 15, 6, '/',int.max));// " 000/002147/483647"
FormatException:object.Exception;import std.exception : assertThrown;assertThrown!FormatException(format("%d","foo"));
msg, stringfn = __FILE__, size_tln = __LINE__, Throwablenext = null);stringmsg | message of the exception |
stringfn | file name of the file where the exception was created (optional) |
size_tln | line number of the file where the exception was created (optional) |
Throwablenext | for internal use, should always be null (optional) |
format(Char, Args...)(in Char[]fmt, Argsargs)format(alias fmt, Args...)(Argsargs)format takes the format string as templateargument. In this case, it is checked for consistency atcompile-time and produces slightly faster code, because the length ofthe output buffer can be estimated in advance.Char[]fmt | aformat string |
Argsargs | a variadic list of arguments to be formatted |
| Char | character type offmt |
| Args | a variadic list of types of the arguments |
writeln(format("Here are %d %s.", 3,"apples"));// "Here are 3 apples."writeln("Increase: %7.2f %%".format(17.4285));// "Increase: 17.43 %"
auto s =format!"%s is %s"("Pi", 3.14);writeln(s);// "Pi is 3.14"// This line doesn't compile, because 3.14 cannot be formatted with %d:// s = format!"%s is %d"("Pi", 3.14);
sformat(Char, Args...)(return scope char[]buf, scope const(Char)[]fmt, Argsargs);sformat(alias fmt, Args...)(char[]buf, Argsargs)sformat takes the format string as a templateargument. In this case, it is checked for consistency atcompile-time.char[]buf | the buffer where the formatted string should go |
const(Char)[]fmt | aformat string |
Argsargs | a variadic list of arguments to be formatted |
| Char | character type offmt |
| Args | a variadic list of types of the arguments |
buf containing the formatted string.buf isn't large enough to hold the formatted string and aFormatException if formatting did not succeed.NoteIn theory this function should be@nogc. But with the current implementation there are some cases where allocations occur:
char[20]buf;writeln(sformat(buf[],"Here are %d %s.", 3,"apples"));// "Here are 3 apples."writeln(buf[].sformat("Increase: %7.2f %%", 17.4285));// "Increase: 17.43 %"
char[20]buf;writeln(sformat!"Here are %d %s."(buf[], 3,"apples"));// "Here are 3 apples."// This line doesn't compile, because 3.14 cannot be formatted with %d:// writeln(sformat!"Here are %d %s."(buf[], 3.14, "apples"));