Monday, 18 July 2011

Format Strings Explained with ASP.NET 4.0 and C#


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

I just signed up at Server Intellect and couldn't be more pleased with my fully scalable & redundant cloud hosting! Check it out and see for yourself.

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.

Yes, it is possible to find a good web host. Sometimes it takes a while to find one you are comfortable with. After trying several, we went with Server Intellect and have been very happy thus far. They are by far the most professional, customer service friendly and technically knowledgeable host we've found so far.

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. 

Check the project source to see tons of format string examples!

No comments:

Post a Comment