Created
August 21, 2012 14:07
-
-
Save JustLikeIcarus/3415828 to your computer and use it in GitHub Desktop.
Phone Format Function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.