Formatting Numerical Data in C#

C# ships with several inbuilt formatting specifies which can be used to quickly format a number, for example the ‘c’ specifier will format the number as a currency:

double dbl1 = 9999999.9999999;
outputStr = string.Format("This is the currency format {0:c}", dbl1);

This will output the numerical value as a currency based on the user’s current currency setting. In my case this will output:

This is the currency format $10,000,000.00

Note firstly that String.Format is a static method – ie you can not use it from an instance of a string object so the below code will generate a compile error:

string outputStr;
outputStr.Format("This is the currency format {0:c}", dbl1);

You must always use it at the class level (ie String.Format)

Below are the inbuilt formatting specifiers:
c – Currency
d – Decimal
e – Exponential notation
f – Fixed point formatting
n – Numerical formatting (with commas)
x – Hexidecimal

The below code shows an implementation of the n formatting speficier:

double dbl1 = 9999999.9999999;
string outputStr;
outputStr = string.Format("This is the numerical format {0:n}", dbl1);
Response.Write(outputStr);

This outputs

This is the numerical format 10,000,000.00

Note that there will be compile errors if you attempt to format a double using the decimal format. Also, note that hexidecimal expects an integer type.

 

Twitter Digg Delicious Stumbleupon Technorati Facebook Email
Uncategorized

No comments yet... Be the first to leave a reply!