How to format a string as a telephone number in C#
Please note, this answer works with numeric data types (int, long). If you are starting with a string, you'll need to convert it to a number first. Also, please take into account that you'll need to validate that the initial string is at least 10 characters in length.
From a good page full of examples:
String.Format("{0:(###) ###-####}", 8005551212);
This will output "(800) 555-1212".
Although a regex may work even better, keep in mind the old programming quote:
Some people, when confronted with a problem, think “I know, I’ll use regular expressions.” Now they have two problems.
--Jamie Zawinski, in comp.lang.emacs
I prefer to use regular expressions:
Regex.Replace("1112224444", @"(\d{3})(\d{3})(\d{4})", "$1-$2-$3");
You'll need to break it into substrings. While you could do that without any extra variables, it wouldn't be particularly nice. Here's one potential solution:
string phone = i["MyPhone"].ToString();
string area = phone.Substring(0, 3);
string major = phone.Substring(3, 3);
string minor = phone.Substring(6);
string formatted = string.Format("{0}-{1}-{2}", area, major, minor);
I suggest this as a clean solution for US numbers.
public static string PhoneNumber(string value)
{
if (string.IsNullOrEmpty(value)) return string.Empty;
value = new System.Text.RegularExpressions.Regex(@"\D")
.Replace(value, string.Empty);
value = value.TrimStart('1');
if (value.Length == 7)
return Convert.ToInt64(value).ToString("###-####");
if (value.Length == 10)
return Convert.ToInt64(value).ToString("###-###-####");
if (value.Length > 10)
return Convert.ToInt64(value)
.ToString("###-###-#### " + new String('#', (value.Length - 10)));
return value;
}