String Formatting FAQ
My String Formatting in C# article has been one of the most popular on this site for the last two years, and it’s received dozens of comments, many of which were formatting questions or answers to formatting questions. This article is a round-up of those comments – all credit to the original commenters, whose comments are on the original article.
| Q: |
How do I show numbers with 5 fixed digits with leading zeroes |
| A: |
int _num1 = 123; int _num2 = 45; int _num3 = 123456; String.Format("{0:00000}", _num1); //"00123"
String.Format("{0:00000}", _num2); //"00045"
String.Format("{0:00000}", _num3); //"123456"
String.Format("{0:d5}", _num1); //"00123"
String.Format("{0:d5}", _num2); //"00045"
String.Format("{0:d5}", _num3); //"123456"
|
| Q: |
Can I substitute a string for a value? |
| A: |
Yes: String.Format("{0:yes;;no}", value)
This will print "no" if value is 0, "yes" if value is 1. |
| Q: |
What’s the most efficient way to convert a type into a string? |
| A: |
Double testDouble = 19.95; String testString1 = String.Format("{0:C}", testDouble); // Boxing operation required. String testString2 = testDouble.ToString(”C”); // No boxing operation required. |
| Q: |
How can I format as percentage without having the number multiplied by 100? |
| A: |
Put a single quote (’) before the % in the format string. myString.Format("{0:##.00′%", 1.23);
This will yield "1.23%". |
| Q: |
Can I convert a number with a thousand separator to an int? |
| A: |
Yes – no matter what thousand separator is in use for your locale. int x = int.Parse("1,345"); // fails int x = int.Parse("1,345",System.Globalization.NumberStyles.AllowThousands) This gives you an x of 1345. |
| Q: |
How can I use curly brackets within a formatted number? |
| A: |
Yes – doubling them escapes them. For example: string.format("{{SomeString}}={0}","Hello"); |
| Q: |
How can I convert from currency back to a number? |
| A: |
You can add the bitmapped values of the Globalization.NumberStyles enumeration. // format double to currency
str = string.Format("{0:c}", pmt);
// parse currency formatted string to double
double.Parse(str, Globalization.NumberStyles.AllowCurrencySymbol +
Globalization.NumberStyles.AllowDecimalPoint +
Globalization.NumberStyles.AllowThousands);
|
| Q: |
So what do google ads G Strings for men have to do with your site? |
| A: |
Ask Google! :) |
| Q: |
What’s a good way to format currency? |
| A: |
double val = 4219.6;
str = string.Format("{0:$#,#.00;Call Us;Call Us}", val);
This will return "$4,219.60". The .00 will force 2 decimals and the “;Call Us;Call Us” to show the text “Call Us” in place of negative and null values respectively. (Just in case) |
| Q: |
How do I format an integer, with commas for thousands? |
| A: |
string str = string.Format("{0:#,0}", intValue);
|
| Q: |
How can I format a phone number to look like 800.555.1212? |
| A: |
There’s no direct way to do this; however you can get dashes in the output. So you can do this: string tempStr = String.Format(”{0:###-###-####}”, 8005551212);
string result =tempStr.Replace(’-',’.');
|
September 30th, 2007 at 8:25 pm
Great post! Here’s a .NET Format String Cheat Sheet I made awhile back: http://john-sheehan.com/blog/index.php/net-cheat-sheets/
October 1st, 2007 at 9:19 pm
[...] SteveX Compiled » Blog Archive » String Formatting FAQ String Formatting FAQ (tags: Programmazione .Net programming) Posted in Link. [...]
December 27th, 2007 at 12:10 pm
[...] And here is the link to the best info I could find on string formatting. [...]
June 26th, 2008 at 7:21 am
Godd stuff !!
It would be a good idea to extend this FAQ by adding more and more samples :-).
My two cents, I need to format a float with the following format ddd,dd
protected string DetailIncurredFormatHourEntryInHHHMM(float currValue)
{
return string.Format(“{0:###,#.00}”, (currValue));
}
October 10th, 2008 at 8:50 am
How can I convert a percentage back to a number? I’ve tried the obvious bitmapped values from the Globalization.NumberStyles enumeration but no luck… I haven’t tried every one from the list but I thought it is a good question to add to this FAQ list!
October 29th, 2008 at 1:37 pm
[...] to pop the month name in the newly created textboxes. SteveX has a super helpful reference and FAQ for string formatting. Thanks, [...]
December 5th, 2008 at 10:01 am
[...] formatting using the String.Format() function, so I created this one (which has also spawned this String Formatting FAQ and strangely enough, this [...]
February 10th, 2009 at 7:00 am
Hi helping hands,
plz tell me the format of displaying a fraction 2 5/10 (2.05 actual value) by using the format as follows
‘###,###,###,##0 ##/10′.
plz kindly reply me soon.MAIL me at gopikrishnareddy.konda@gmail.com
regards,
GKR.
May 4th, 2009 at 12:36 pm
Hi,
Could you please show me how to convert a number to string without an exponent?
E.g.
1) when I execute this: MaxVal=UnsignedLong.MaxValue – 1
I get this – 1.84467440737096E+19
But I want this – 18446744073709551614
2) when I execute this: CDbl(“112345678908765432345345456577.2342″).ToString
I get this – 1.12345678908765E+29
But I want the exact same number
There are many numeric datatypes I am working with here, and also deal with numbers having varying decimals. I would like to write some generic code that can convert a number to string irrespective of the decimal places.
Thanks in advance!
September 29th, 2009 at 11:35 am
How to do the following formatting:
$1,43,21,000.00
October 7th, 2009 at 8:28 pm
[...] formatting using the String.Format() function, so I created this one (which has also spawned this String Formatting FAQ and strangely enough, this [...]
October 13th, 2009 at 10:40 am
Does anyone know a way to introduce scale when using format strings?
e.g if had a string value that was “40092″ i could convert this to a decimal using Convert.ToDecimal(string.Format(“{0:#0.00}”, myValue));
this would return the value 40092.00
however, what if i wanted to introduce scale to it? i.e i would like my returned value to be 400.92. is there anyway to accomplish this using string.format format string method?