views:

1050

answers:

9

If I had a phone number like this

string phone = "6365555796";

Which I store with only numeric characters in my database (as a string), is it possible to output the number like this:

"636-555-5796"

Similar to how I could if I were using a number:

long phone = 6365555796;
string output = phone.ToString("000-000-0000");

I've tried searching and all I could find online were numeric formatting documents.

The reason I ask is because I think it would be an interesting idea to be able to store only the numeric values in the DB and allow for different formatting using a Constant string value to dictate how my phone numbers are formatted. Or am I better off using a number for this?

EDIT: The question is to format a string that contains numbers, not a number itself.

+1  A: 

Why not just do something like this?

string phoneText = "6365555796";
long phoneNum = long.Parse(phoneText);
string output = phoneNum.ToString("000-000-0000");
Stu Mackellar
That's an interesting idea, but if I want to include the numbers in an ASP.NET Gridview or a Repeater it would require extra code to output the numbers correctly. I was wondering if there was a one-line .NET function I was somehow overlooking...
Dan Herbert
You already have the answer by swilliams. But you can employ this functionality as well in "one line" if you use anonymous delegate.
Sunny
If the number has leading 0, then you might get erroneous output
faulty
A: 

You could potentially do a string insert at a given character point. Kinda like: phone = phone.Insert(3, "-"); phone = phone.Insert(7, "-");

Jeremy Reagan
This is "slow", as it will lead to a lot of string creations.
Sunny
It should be faster then parsing a long, though.
configurator
A: 

To control string format of a number for display in an ASP.NET Gridview or another control, you can wrap your item in a helper class for display purposes:

public class PhoneDisplay
{
    long phoneNum;
    public PhoneDisplay(long number)
    {
        phoneNum = number;
    }
    public override string ToString()
    {
        return string.Format("{0:###-###-####}", phoneNum);
    }

}

Then, define data or display fields as (e.g.):

PhoneDisplay MyPhone = new PhoneDisplay(6365555796);
gimel
+4  A: 

I think this works

string s = string.Format("{0:###-###-####}", ulong.Parse(phone));

In addtion, this http://blog.stevex.net/index.php/string-formatting-in-csharp/ is a nice post on formatting strings in .NET.

Thanks to @swilliams for clarifications.

AJ
Heh, I had copied the URL to paste it onto my post, but forgot to for some reason...
swilliams
you're way ahead of me!
AJ
+6  A: 

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));
Esteban Brenes
+5  A: 

Be aware that not everyone uses the North American 3-3-4 format for phone numbers. European phone numbers can be up to 15 digits long, with significant punctuation, e.g. +44-XXXX-XXXX-XXXX is different from 44+XXXX-XXXX-XXXX. You are also not considering PBXs and extensions, which can require over 30 digits.

Military and radio phones can have alphabetic characters, no this is not the "2" = "ABC" you see on touch-tone phones.

Dour High Arch
My app. is only storing US numbers in the 10 digit format. If extensions are needed they will be stored in a separate field. We're storing numbers for comparison since phone numbers entered will need to be compared and stripping out all non-numerics guarantees user formatting won't break that.
Dan Herbert
+5  A: 

The simple version:

string phone = "6365555796";
Convert.ToInt64(phone).ToString("000-000-0000");

To wrap some validation around that and put it in a nice method:

string FormatPhone(string phone)
{
   /*assume the phone string came from the database, so we already know it's
     only digits.  If this changes in the future a simple RegEx can validate 
     (or correct) the digits requirement. */

   // still want to check the length:
   if (phone.Length != 10) throw new InvalidArgumentException();

  return Convert.ToInt64(phone).ToString("000-000-0000");
}
Joel Coehoorn
+1  A: 

I loves me some extension method action:

   /// <summary>
   ///   Formats a string of nine digits into a U.S. phone number.
   /// </summary>
   /// <param name="value">
   ///   The string to format as a phone number.
   /// </param>
   /// <returns>
   ///   The numeric string as a U.S. phone number.
   /// </returns>
   public static string
   ToUSPhone (this string value)
   {
      if (value == null)
      {
         return null;
      }

      long  dummy;

      if ((value.Length != 10) ||
         !long.TryParse (
            value,
            NumberStyles.None,
            CultureInfo.CurrentCulture,
            out dummy))
      {
         return value;
      }

      return string.Format (
         CultureInfo.CurrentCulture,
         "{0}-{1}-{2}",
         value.Substring (0, 3),
         value.Substring (3, 3),
         value.Substring (6));
   }
Jesse C. Slicer
A: 

Sure:

Regex.Replace(phone, @"^(\d{3})(\d{3})(\d{4})$", @"$1-$2-$3")

Of course, now you have 2 problems.

Mark Brackett