How to Format a String as a Telephone Number in C#

Format String as phone number in C#

You might want to use regex for this. The regex for North America phone number looks like this

^(\(?[0-9]{3}\)?)?\-?[0-9]{3}\-?[0-9]{4}$

I guess you can use Regex.Replace method in C#.

Fastest way to format a phone number in C#?

String.Format("{0:(###) ###-#### x ###}", double.Parse("1234567890123"))

Will result in (123) 456-7890 x 123

Format string as UK phone number

UK telephone numbers vary in length from 7 digits to 10 digits, not including the leading zero. "area" codes can vary between 2 and usually 4 (but occasionally 5) digits.

All of the tables that show the area code and total length for each number prefix are available from OFCOM's website. NB: These tables are very long.

Also, there's no standard for exactly where spaces are put. Some people might put them in difference places depending on how "readable" it makes the resulting text.

formatting string/phone number

Is the phone number stored as a string or a numeric value. If it's stored as an integral value, this should do it:

string formattedPhone = rawNumber.ToString( "(#00) 000-0000" ) ;

If it's stored as a string, you'll need to look at the length and start chopping it up, thus:

static string FormatAsPhoneNumber( string s )
{
if ( s == null ) throw new ArgumentNullException() ;
if ( s.Length > 10 ) throw new ArgumentOutOfRangeException() ;

StringBuilder sb = new StringBuilder() ;
int p = 0 ;
int remaining = s.Length ;

if ( remaining > 7 )
{
int areaCodeLength = remaining - 7 ;

sb.Append("(").Append(s.Substring(p,areaCodeLength)).Append(") ") ;

p += areaCodeLength ;
remaining -= areaCodeLength ;

}
if ( remaining > 4 )
{
int exchangeLength = remaining - 4 ;

sb.Append(s.Substring(p,exchangeLength)).Append("-") ;

p += exchangeLength ;
remaining -= exchangeLength ;

}

sb.Append(s.Substring(p) ) ;

string formatted = sb.ToString() ;
return formatted ;
}

Results:

Raw         Formatted
---------- --------------
1 1
12 12
123 123
1234 1234
12345 1-2345
123456 12-3456
1234567 123-4567
12345678 (1) 234-5678
123456789 (12) 345-6789
1234567890 (123) 456-7890

String.Format is not formatting phone number

You are using numeric formating ("{0:###-###-####}") on a string customer.ContactHome that's why it's not working.

Can I Format A String Like A Number in .NET?

Best I can think of without having to convert to a long/number and so it fits one line is:

string number = "1234567890";
string formattedNumber = string.Format("{0}-{1}-{2}", number.Substring(0,3), number.Substring(3,3), number.Substring(6));

String.Format Phone Numbers with Extension

I think you'll have to break your phoneDigits string into the first 10 digits and the remainder.

//[snip]
else if (phoneDigits.ToString().Length > 10)
{
return String.Format("{0:(###) ###-#### x}{1}", phoneDigits.Substring(0,10), phoneDigits.Substring(10) );
}
//[snip]


Related Topics



Leave a reply



Submit