Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

formatting string/phone number

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.

like image 957
DotnetSparrow Avatar asked Oct 23 '25 18:10

DotnetSparrow


2 Answers

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);
}
like image 52
Erick Petrucelli Avatar answered Oct 25 '25 06:10

Erick Petrucelli


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
like image 29
Nicholas Carey Avatar answered Oct 25 '25 07:10

Nicholas Carey