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?
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?
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
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?
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.
What about formating prices with optional pence/cents: i.e. 123.3452 -> 123.34 but 123.0000 -> 123
Good examples how to format float numbers are also here C# String Format.
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