C# 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 these were additional formatting questions, or answers to those 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");
will produce: "{SomeString}=Hellow"

 
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(’-',’.'); 

11 Responses to “C# String Formatting FAQ”

  1. Jimmy Tang Says:

    String.format(“{0:###\\.###\\.####}”, 8005551212)

    “800.555.1212″

  2. Mukesh Says:

    i have a number : 123 , i want convert to this number in 0.0123 format. plz help me.

  3. Mukesh Says:

    i input 11202007 in date this is automatically converted in leave event in textbox to date format .
    and i input time 173000 this is also converted to time format. so help me:-(

  4. Ace McGuire Says:

    Alteration to:

    Q: How can I format as percentage without having the number multiplied by 100?
    A: Put a single quote (’) before AND AFTER the % in the format string.

    myString.Format(“{0:##.00′%′”, 1.23);

    This will yield “1.23%”.

    …without 2 single quotes, any additional formatting instructions (for negative &zero) with simple output to your display.

  5. Tom Says:

    Hi,

    Q: How can I format a string: 165484 to read 165.5?

  6. Ross Says:

    how can I change the formatting output of individual characters in a string?
    eg:
    string myString = “abcdefghij”;

    And I want my output to look like => “(ab)cd-efghij”

    ie: its placed in some ( ) brackets and a – hyphen? prolly getting beyond the realms of what can be done huh?

  7. Simon Hawkin Says:

    Use backslash to escape characters which would otherwise have a special meaning (“control characters”). For example, you can use “\{” to represent the left curly brace.

    Use @”" notation (at-sign before the string) to cancel special processing of control characters. Eg @”c:\windows” is the same as “c:\\windows”.

  8. Todd Elliott Says:

    Is there a way to change the format string to include an extension of any length?

    For instance, in C#:
    work column is a Datagridview column set up in code.

    Example number, 8002223333
    workColumn.DataFormatString = “{0:(###) ###-####}”;
    Would return 800-222-3333.

    But if I had an extension of 4444, that same number returns:
    (8002223) 333-4444

    I need it to format the 1st ten numbers normally, with the extension at the end no matter how long.
    For instance:
    (800) 222-3333:4444

  9. Willy Launch Says:

    Where is that Google G String ad again :-)

  10. ARAVIN Says:

    How can I convert string into UUID(128 bit representation)
    plz help me

  11. Ed Says:

    Hi,

    I’m trying to format a string in a textbox. The string takes the form of something like L00590501 and I’d like it to display in the textbox as L/0059/05/01. I don’t want to add the slashes to the string as when it is saved to the DB I want it in the original format. Therefore I only want to format the string for display purposes. How so I go about that?

    Thanks,
    Ed

Leave a Reply

buy cheap Endep online buy cheapest Endep and Endep how to order Amitriptyline online without prescription buy Amitriptyline without rx from us pharmacy online Amitriptyline purchase purchase online prescription Amitriptyline without purchasing Amitriptyline online without prescription order generic Amitriptyline buy Endep no prescriptions how to order Endep online without prescription comprare Endep generico Endep online buy Endep in england buy cheap Endep online free consult Endep purchased online without prescription what is Endep Endep tabletten buy Endep no perscription cod Endep non rx fedex overnight free want to buy Anafranil in usa Aricept overdose buy discount Aricept on line Aricept buy Aricept online Aricept order buy Aricept pills Nizoral suppliers cheap order rx Nizoral canada Nizoral order Nizoral usa cod comprar Nizoral generico buy Nizoral 200 mg buy cheap Nizoral under without rx buy cheap Nizoral with dr. prescription Prozac 200 mg buy Lisinopril australia el Nizoral generico buy Lisinopril tablets without rx next day delivery Lisinopril with no script buy Lisinopril c o d purchase arimidex no scams order Arimidex order amex Arimidex canadian pharmacy buy Arimidex without doctor order rx free Arimidex buy Abilify with american express buy Abilify cod order Finpecia without a prescription cheap order rx Finpecia purchase Famvir no visa online without prescription buy Famvir paypal without rx buy Famvir without Famvir without prescription medications Famvir without persription purchase Famvir online no membership overnight shipping Famvir no physician approval Amitriptyline purchase order Amitriptyline free next day airAmitriptyline on line Valtrex no rx needed cod accepted buy next day Fluoxetine buy Fluoxetine line purchase Fluoxetine cod delivery buy Fluoxetine 20 mg purchase Fluoxetine buy cheap Fluoxetine under without rx purchase Fluoxetine visa without prescription Fluoxetine by mail Fluoxetine for pets Fluoxetine 10mg Amitriptyline purchase online how to order Famvir online without a rx Prozac Amitriptyline no perscription Famvir next day purchase Anafranil no prescription cheap buy cheapest Anafranil next day delivery on Anafranil saturday Anafranil buy Anafranil buy Anafranil overnight where to purchase Anafranil no prescription no fees Anafranil drug buy Lisinopril where Lisinopril buy on line order Lisinopril online no membership overnight shipping no prescription required for Lisinopril order maxalt cash on delivery Maxalt from canada buy cheapest Maxalt purchase Maxalt visa without prescription buy Maxalt uk Maxalt 10 mg purchase Maxalt no visa online without prescription purchase generic Lisinopril online Lisinopril no prescription to buy maxalt order online no membership overnight how to get a arimidex rx Aricept without a perscription fedex Aricept overnight without a prescription Donepezil prescription order buy genuine Aricept Aricept uk sales prescription Proscar buy Proscar pay cod Maxalt apotheke buy no perscription Proscar purchase Proscar online buy cheap fedex Prednisone maxalt with no presciption buy Maxalt shipped cod Proscar online Prednisone order buy Amitriptyline with amex Accutane 40 mg delivered overnight buy brand Accutane 40 mg Accutane 40 mg orderd online without prescription where to purchase generic Accutane 40 mg online without a rx how to get 40 mg Accutane without next day delivery 40 mg Accutane with no script buy Amitriptyline online Accutane 40 mg online no prescription buy Accutane 40 mg online us pharmacy Accutane 40 mg best buy buy Accutane 40 mg c o d order 40 mg Accutane cash on delivery no presciption 40 mg Accutane