I want to format the phone numbers using C#. Format is (XX) YYY-ZZZZ or(XXX) YYY-ZZZZ. So, I need to format the right seven digits and then remaining two or three for area code.
{EDIT}
Phone is saved as a plain string /VARChar of length 9 or 10
Please suggest solution.
Thanks.
If I understood right, you want a function that receives an int and returns a string with the fone number on that format. If so you can do something like:
public string GetPhoneNumber(int number) {
string n = number.ToString();
if (n.Length == 9)
return "(" + n.Substring(0, 2) + ") " + n.Substring(2, 3) + "-" + n.Substring(5, 4);
else
return "(" + n.Substring(0, 3) + ") " + n.Substring(3, 3) + "-" + n.Substring(6, 4);
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With