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?

7 thoughts on “Custom string formatting in C#”

  1. 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. 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?

  3. 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.

  4. 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>