Search notes:

.NET: format strings

The default format string for numbers, dates and enumerations is G.

Format strings for different data types

Numbers

A numerical format string of two parts:
  • The format specifier (which is a single character), and a
  • an optional precision specifier whose range is 0 … 99
Format specifiers are:
C, c Currency
D, d Decimal
E, e Exponential (scientific) notation
F, f Fixed-point
G, g Choses the more compact representation of F or E.
N, n Number, with group (thousand) separator
P, p Percent
R, r Round-trip, recommended for System.Numerics.BigInteger
X, x Hexadecimal representation
All other characters throw a FormatException.

Dates

d, dd Day, two digit day of the month: 1 … 31 and 01 … 31, respectively
ddd, dddd Abbreviated and full name of the day of the week.
ffffffff The tenths of a second … the ten millionths of a second
FFFFFFFF If non-zero: the tenths of a second … the tenths millionths of a second in a date and time value.
FFFFFFF If non-zero, the ten millionths of a second in a date and time value.
g, gg The period or era. (for example A.D.)
h, hh The hour and two digit hour using a 12-hour clock (1 … 12 and 01 … 12, respectively)
H, HH The hour and two digit hour using a 24-hour clock (1 … 24 and 01 … 24, respectively)
K Time zone information, for example +01:00. Cannot be only specifier in format string.
m, mm The minute or two digit minute (0 … 59 and 00 … 59, respectively)
M, MM The month, 1 … 12 and 01 … 12, respectively
MMM, MMMM Abbreviated and full name of the month
s, ss Seconds, 0 … 59 and 00 … 59, respectively
t, tt The first character, both characters of AM or PM
y, yy year, 0 … 99 and 00 … 99, respectively
yyy year with a minimum of three digits.
yyyy, yyyyy four and five digit year
z, zz Hours offset from UTC UTC
zzz Hours and minutes offset from UTC.
: The time separator.
"/" The date separator.
"string", 'string' Literal string delimiter.
% Defines the following character as a custom format specifier.
\ The escape character.
All other characters are not intepreted.

Enumeration

G, g If possible: string representation of enum entry, otherwise its integer value. Flags of flag-enums are separated by commas
F, f String representation of enum entry if possible. ? Flag values separated by commas ?
D, d Integer value of enum entry.
X, x Hexadecimal representation of integer value

Extensibility

In .NET, string formatting can be extended with the System.IFormattable and System.ICustomformatter interfaces.

See also

C-Sharp: verbatim and interpolated strings
The PowerShell -f operator (which formats strings)

Index