May 11, 2011

Format Strings Explained with 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
Long Date 
Full Date Time 
Month Day 
Short Time 
Long Time 
Month Year 

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:

int intData = 123456;
//Output currency
Response.Write(intData.ToString("C"));
Response.Write("<br/>"); //new line


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:

double dblData = 12345.6789;
//Output fixed-point to specific precision


Response.Write(dblData.ToString("F3"));
Response.Write("<br/>"); //new line


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. 


No comments:

Post a Comment