String.Format Phone Numbers with Extension
Posted
by ChiliYago
on Stack Overflow
See other posts from Stack Overflow
or by ChiliYago
Published on 2010-03-08T18:38:03Z
Indexed on
2010/03/08
18:51 UTC
Read the original article
Hit count: 381
I am trying to create a an function that formats US phone numbers -- hopefully without looping through each digit.
When 10 digits are passed in all is fine. How ever when more than 10 digits are passed in I want the String.Format method to append the extension digits on the right. For example:
When 14 digits passed in the result should be:(444)555-2222 x8888 When 12 digits passed in the result should be:(444)555-2222 x88 etc. However what I get with my current attempt is: Passing in 12 digits returns this string '() -949 x555444433'
here is what I have so far.
public static string _FormatPhone(object phonevalue)
{
Int64 phoneDigits;
if (Int64.TryParse(phonevalue.ToString(), out phoneDigits))
{
string cleanPhoneDigits = phoneDigits.ToString();
int digitCount = cleanPhoneDigits.Length;
if (digitCount == 10)
return String.Format("{0:(###) ###-####}", phoneDigits);
else if (digitCount > 10)
return String.Format("{0:(###) ###-#### x#########}", phoneDigits);
else
return cleanPhoneDigits;
}
return "Format Err#";
}
Thanks in advance.
© Stack Overflow or respective owner