CSharp - Standard Format Strings and Parsing Flags

Introduction

The standard format strings control how a numeric type or DateTime/DateTimeOffset is converted to a string.

There are two kinds of format strings:

  • Standard format strings, consists of a single letter, followed, optionally, by a digit. An example is "C" or "F2".
  • Custom format strings, create your own template. For example is "0:###,#.000E+00".

Numeric Format Strings

The following table lists all standard numeric format strings.

Letter
Meaning
Sample input
Result
Notes
G or g




"General"




1.2345, "G"
0.00001, "G"
0.00001, "g"
1.2345, "G3"
12345, "G3"
1.2345
1E-05
1e-05
1.23
1.23E04
Switches to exponential notation
for small or large numbers
G3 limits precision to three digits
in total, before + after point

F

Fixed point

2345.678, "F2"
2345.6, "F2"
2345.68
2345.60
F2 rounds to two decimal places

N


Fixed point with
group separator
("Numeric")
2345.678, "N2"
2345.6, "N2"

2,345.68
2,345.60

As above, with group (1000s)
separator

D


Pad with leading
zeros

123, "D5"
123, "D1"

00123
123

For integral types only
D5 pads left to five digits; does
not truncate
E or e


Force
exponential
notation
56789, "E"
56789, "e"
56789, "E2"
5.678900E+004
5.678900e+004
5.68E+004
Six-digit default precision


C


Currency


1.2, "C"
1.2, "C4"

$1.20
$1.2000

C with no digit uses default
number of D.P. from format
provider
P



Percent



.503, "P"
.503, "P0"


50.30 %
50 %


Uses symbol and layout from
format provider
Decimal places can optionally be
overridden
X or x


Hexadecimal


47, "X"
47, "x"
47, "X4"
2F
2f
002F
X for uppercase hex digits; x for
lowercase hex digits
Integrals only
R or G17



Round-trip



1f / 3f, "R"



0.333333343



For the float and double
types, R or G17 squeeze out all
digits to ensure exact round-
tripping