Alex Rivera | Logout

How to format a string as a telephone number in C#

Asked 2008-10-09T18:19:37.327
195

I have a string "1112224444' it is a telephone number. I want to format as 111-222-4444 before I store it in a file. It is on a datarecord and I would prefer to be able to do this without assigning a new variable.

I was thinking:

String.Format("{0:###-###-####}", i["MyPhone"].ToString() );

but that does not seem to do the trick.

** UPDATE **

Ok. I went with this solution

Convert.ToInt64(i["Customer Phone"]).ToString("###-###-#### ####")

Now its gets messed up when the extension is less than 4 digits. It will fill in the numbers from the right. so

1112224444 333  becomes

11-221-244 3334

Any ideas?

Edit
Report

2 Answers

202

I prefer to use regular expressions:

Regex.Replace("1112224444", @"(\d{3})(\d{3})(\d{4})", "$1-$2-$3");
answered 2008-10-09T18:36:07.947
0

To take care of your extension issue, how about:

string formatString = "###-###-#### ####";
returnValue = Convert.ToInt64(phoneNumber)
                     .ToString(formatString.Substring(0,phoneNumber.Length+3))
                     .Trim();
answered 2010-09-24T21:11:12.790

Your Answer