CodingIsSwell
CodingIsSwell

Reputation: 145

Curious about Format function with Phone Number

UPDATE (SOLVED): https://dotnetfiddle.net/6GEJyO


I used the following code to format a phone number in a loop with various formats:

string PhoneNumber = "9998675309"
String.Format("{0:" + formatString + "}", Convert.ToDouble(PhoneNumber))

I need to format phone numbers two slightly different ways. One came out as I expected and the other did not.

So, curious, I decided to do a quick console app and see all of the different phone number formatting possibilities I could think of. Here is that result:

http://i.imgur.com/PfKlZfM.png

My question is this: Why do some of those come out formatted the way that they seem like they should and others do not? Are there escape characters that are needed for some of them?

Upvotes: 2

Views: 78

Answers (1)

Elian Ebbing
Elian Ebbing

Reputation: 19027

The "." has a special meaning in a format string. Determines the location of the decimal separator in the result string. So you have to escape the ".":

string formatString = "###-###\\.####";

Some examples of the usage of the "." in format strings:

// the result is "3.40"
(3.4).ToString("#.00", CultureInfo.GetCultureInfo("en-US"))

// the result is "3,142"
(3.141592).ToString("#.000", CultureInfo.GetCultureInfo("nl-NL"))

Upvotes: 5

Related Questions