C# Custom Number Formatting

Very often the inbuilt numerical formatting in C# will be insufficent and you will want to apply the custom formatting for your numbers.

The String.Format method is very flexible and can be used to apply custom formatting rules. The # character informs the Format method how to format the numerical value, for example to forma the number 12000.12 as 12,000.12 use can use the format “#,#.##” as in the below code:

double dbl1 = 12000.12;
string outputStr;
outputStr = string.Format("This is a custom formatting example  {0:#,#.##} ", dbl1);
Response.Write(outputStr);

In this example the , character is used to denote the thousand separator and the ## after the decimal place denotes that a maximum of 2 numbers should appear after the decimal place. Therefore the double 12000.1 would be formatted as 12,000.1, if you wish two decimals places always to be shown (ie 12,100.10 in this case) you should use the ’0′ character after the decimal place:

outputStr = string.Format("This is a custom formatting example  {0:#,#.00} ", 12000.1);

You can also add additional characters before and after the formatting string. Thus to format the value as $ 12,000.12 use the format string “$ #,#.##” , or even “#,#.## US Dollars” would output “12,000.12 US Dollars”.

The % character will multiply the value by 100 and then add % character to the end of the string. Thus for the double value 12 the format string “{0:0.00 %}” will output “1200.00 %”. Note that you can use the # character in place of the 0 character as per the formatting rules above and so “#,#.## %” in this case would output “1,200 %”.

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

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