String formatting in .NET C# is easy – the hard part is looking up what all the formatting specifiers do. I find myself constantly checking the (rather wordy) .NET documentation just to format a date or a currency value. This cheat sheet brings all the String.Format formatting specifiers together in one easy overview. How to […]

This article was posted by Independent Software, a website and database application development company based in Maputo, Mozambique. Our website offers regular write-ups on technical and design issues, ranging from details at code level to 3D Studio Max rendering. Read more about Independent Software's philosophy, or get in touch with Independent Software.

String formatting in .NET C# is easy – the hard part is looking up what all the formatting specifiers do. I find myself constantly checking the (rather wordy) .NET documentation just to format a date or a currency value. This cheat sheet brings all the String.Format formatting specifiers together in one easy overview.

How to format

The String.Format method is your friend. It can format any number of arguments into a string, like so:

which returns

Wherever you want String.Format to insert a formatted value, place curly braces containing the index of the argument (0 being the first argument, 1 being the second and so on). The String.Format method will format your arguments according to its default formatting rules (depending on the argument types) and place them in the result string. But what if you want your values formatted in a special way? You use formatting specifiers like so:

returns

In other words, you place a colon and a formatting specifier after the argument index.

Formatting Numbers

Standard Numeric Format Strings

SpecifierTypeFormatSample (36.45)Sample (-12345)
c/CCurrency{0:c}$36.45(-$12,345.00)
d/DDecimal{0:d}Exception-12345
e/EScientific{0:e}3.645000e+001-1.234500e+004
f/FFixed-point{0:f}36.45-12345.00
g/GGeneral{0:g}36.45-12345
n/NNumber with thousand separator{0:n}36.45-12,345.00
p/PPercentage{0:0}3,645.00 %1,234,500.00 %
r/RRound-trip{0:r}36.45Exception
x/XHexadecimal{0:x}Exceptionfffcfc7

Comments

  • Round-trip formatting is converting a number to a string in such a way that it can be converted back into the same number. This conversion is only supported for single and double types.
  • Currency conversion will use the currency symbol, thousands and decimal separators specified by the current Culture.
  • Percentage conversion multiplies the number by 100, then adds a percentage sign.

Precision

Each number formatting specifier can be accompanied by a precision (if omitted, the default precision is assumed):

SpecifierTypeFormatPrecision specifier functionDefault precisionSample (precision 6)Result
c/CCurrency{0:c6}Number of decimal digitsDefined by System.Globalization .NumberFormatInfo3.45$3.450000
d/DDecimal{0:d6}Minimum number of digitsMinimum number of digits required123000123
e/EScientific{0:e6}Number of decimal digits63.453.450000e+000
f/FFixed-point{0:f6}Number of decimal digitsDefined by System.Globalization .NumberFormatInfo3.453.450000
g/GGeneral{0:g6}Number of significant digitsDepends on numeric type3.353.45
n/NNumber with thousand separator{0:n6}Desired number of decimal placesDefined by System.Globalization .NumberFormatInfo3.453.450000
p/PPercentage{0:p6}Desired number of decimal placesDefined by System.Globalization .NumberFormatInfo0.34534.500000 %
r/RRound-trip{0:r6}Ignored3.453.45
x/XHexadecimal{0:x6}Number of digits in the result string345000159

Custom Number Formatting

Beyond the standard numeric format strings, you can define your own specific formatting. You can mix and match the following:

SpecifierTypeSampleValueResult
0Zero placeholder{0:0000.0000}3.4500003.4500
#Digit placeholder{0:#####:##}531.456531.45
.Decimal separator{0:0,000.00}1234.451,234.45
,Thousands separator{0:0,000.00}1234.451,234.45
%Percent sign{0:0.00%}0.4545.00%

Comments

  • The zero placeholder allows you to pad a number with zeroes.
  • The percent sign multiplies a value by 100, then adds a percent sign.

Formatting Dates

SpecifierTypeSample
dShort date08/03/2013
DLong dateFriday, March 08, 2013
fFull date and time, shortFriday, March 08, 2013 10:10 AM
FFull date and time, longFriday, March 08, 2013 10:10:44
gDefault date and time08/03/2013 10:10 AM
MMonth and dayMarch 08
rRFC1123 dateFri, 08 Mar 2013 10:10:44 GMT
sSortable date stirng2013-03-08T10:10:44
tShort time10:10 AM
TLong time10:10:44
uUniversal sortable local time2013-03-08 10:10:44Z
UUniversal GMTFriday, March 08, 2013 08:10:44
YMonth and yearMarch, 2013

Custom Date Formatting

SpecifierMeaningSampleResult
dDay, zero-padded{0:dd}08
ddd3-letter day name{0:ddd}Fri
ddddFull day name{0:dddd}Friday
ffSecond fractions, 2 digits{0:ff}19
fffSecond fractions, 3 digits{0:fff}193
ffffSecond fractions, 4 digits{0:ffff}1934
ggEra{0:gg}A.D.
hhHour (2 digits, 12H){0:hh}10
HHHour (2 digits, 24H){0:HH}10
mmMinutes, zero-padded{0:mm}16
MMMonth, zero-padded{0:MM}03
MMM3-letter month name{0:MMM}Mar
MMMMFull month name{0:MMMM}March
ssSeconds{0:ss}02
ttAM/PM{0:tt}AM
yy2-digit year{0:yy}13
yyyy4-digit year{0:yyyy}2013
zz2-digit timezone offset{0:zz}+02
zzzFull timezone offset{0:zzz}+02:00

Usage

You can now place various custom date formatting specifiers in a formatting string like so:

which yields

Did this article help you out? Please help us find more time to write useful guides & articles like this by donating a buck or two. It'll keep us coffee-fueled. Thanks!

Comments

2 2 Responses to “.NET: String Formatting in C# Cheat Sheet”
  1. Sam says:

    Nicely done, top candidate article for bookmarking =)
    One question though, I sometimes see examples that omit the String.Format(…) part and just place the string and arguments in brackets like: (“Show me the {0}” , “money!”)
    I’ve tried that with no success… any idea?

    Thanks!

  2. Tobias says:

    Could you add spacing to the cheat sheet?
    How the placeholder has to look to make it always 6 characters wide for example or flush left/right?
    Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *