This tutorial will demonstrate how to use format strings and give some examples of specific format strings using ASP.NET 4.0 and C#.

What is a Format String?

Format strings are used to format common data types when converting them to strings. An example of this would be converting some data in an integer to a string in the format of currency. The standard numeric format strings allow us to convert numeric data to the following formats:

Name Format Specifier
Currency C
Decimal D
Exponential E
Fixed-point F
General G
Number N
Percent P
Round-trip R
Hexadecimal X

Furthermore, there are also format strings for other types such as dates and times. Some of the datetime formats are as follows:

Format Pattern Format Specifier
Short Date d
Long Date D
Full Date Time F
Month Day M
Short Time t
Long Time T
Month Year Y

The Syntax

Let’s take a look at an example in which we will convert an integer to a string with the formatting of our currency:

This code will output ‘$123,456.00’. Notice the syntax that we use for the format string. We simply call the ToString method, pass it the format specifier, and it does the rest for us.

Let’s take a look at an example where we want to ouput a double as a string with only a specified number of decimal places:

This code will output ‘12345.679’. Notice, to specify the number of decimals places we simply just need to append a number to the format specifier.
Download Source Files