Skip to content

Instantly share code, notes, and snippets.

@JustLikeIcarus
Created August 21, 2012 14:07
Show Gist options
  • Save JustLikeIcarus/3415828 to your computer and use it in GitHub Desktop.
Save JustLikeIcarus/3415828 to your computer and use it in GitHub Desktop.
Phone Format Function
/// <summary>
/// Formats Phone Numbers to standard formats for display
/// </summary>
/// <param name="pn">Phone Number to format</param>
/// <returns></returns>
public static string FormatPhoneNumber(string pn)
{
if (String.IsNullOrEmpty(pn))
return pn;
string format;
Double phoneNumber = Double.Parse(Regex.Replace(pn, "[^0-9]", ""));
int phoneLength = phoneNumber.ToString().Length;
if (phoneLength == 7)
{
format = "###-####";
}
else if (phoneLength == 11)
{
format = "#-###-###-####";
}
else if (phoneLength == 10)
{
format = "(###) ###-####";
}
else
{
return pn;
}
return phoneNumber.ToString(format);
}
@g1smd
Copy link

g1smd commented Sep 2, 2012

This works for US numbers. For UK numbers, things are much more complex, for example: https://github.com/g1smd/Drupal-CCK-Phone-GB/blob/master/phone.gb.inc in PHP.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment