Custom string formatting in C#

Formatting strings for output into various mediums is always a fun… err.. required task. Every language does it differently. C# overloads the ToString() method to format a string using this syntax:

Console.WriteLine(MyDouble.ToString("C"));

where “C” is a format specifier specifically for locale specific currency formatting. If the variable ‘MyDouble’ was 3456 in the example above, you’d see:

$3546.00

printed out. Of course, the fun doesn’t end there. There are a whole boatload of standard numeric formatting specifiers you can use including decimal, number, percent and hexadecimal. But truly the most fun are the custom numeric format strings. Example: Let’s say that your boss wants you to format all product pricing rounded to the nearest dollar without using a commas (ie: $1224 instead of $1,224.00). Normally, you’d write:

Price: <%= Product.Price.ToString("C") %>

but since you don’t want to have commas, you can use a custom format string:

Price: <%= Product.Price.ToString("$#####") %>

which will produce this:

Price: $1224

How about phone numbers? Don’t they just suck to format? In ColdFusion, you’d have something like this:

(#left(str, 3)#) #mid(str, 4, 3)# - #right(str, 4)#

where ‘str’ is a string containing the 10 digit phone number. In C#, you can write this:

phone.ToString("(###) ### - ####");

Pretty concise isn’t it?

This entry was posted in .NET. Bookmark the permalink.

7 Responses to Custom string formatting in C#

  1. Matthew says:

    From what I can tell the System.String object does not have a overloaded ToString method that has a string parameter. The only methods have no parameters or has a IFormatProvider parameter.

    Is this written in regards to a specific .NET Framework version?

  2. AJ says:

    hi Matthew,

    It’s not the System.String class that I was referencing, but other classes that have a ToString() method, ie:

    Double.ToString()
    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdoubleclasstostringtopic.asp

    Check out the Custom Numeric Format Strings examples here:

    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconcustomnumericformatstrings.asp

    AJ

  3. Jesse says:

    phone.ToString(“(###) ### – ####”);

    I was so hopeful when I found this again because I remember this being the solution the last time I had to format a string.

    But now I am in .NET framework 2.0 and this seems to be gone.

    The .ToString now only accepts an IFormatProvider. Do you know how to adapt to this?

  4. Ashim says:

    Jesse, are you talking about the ToString method in double, int, float or in string class itself?

    If you are talking about string class , i guess that i true in .net 1.1 also.

    try double.parse(your phone string).ToString(“(###) ###-####”);

    remember in your phone string only include digits.

  5. Fred says:

    What about formating prices with optional pence/cents: i.e. 123.3452 -> 123.34 but 123.0000 -> 123

  6. vazbik says:

    Good examples how to format float numbers are also here C# String Format.

  7. Heidi says:

    All this is useless when you have some telephone numbers that start with 0. :(
    There is not and easy way, the best is to write a function

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>