0

I am trying to use the solution provided in this answer, and have also referenced this article.

Basically, I am trying to format a social security number. This is the method used in the articles linked above:

String.Format(“{0:###-##-####}”, 123456789);

This works great when the number is passed in as shown above, but the number I need to format is contained in a string - so I am essentially doing this (which doesn't work):

String.Format(“{0:###-##-####}”, "123456789");

What is a good way to get around my problem?

Community
  • 1
  • 1
drewwyatt
  • 5,989
  • 15
  • 60
  • 106

4 Answers4

3

You can parse the string to numeric type and then use string.Format like:

String.Format("{0:###-##-####}", long.Parse("123456789"));

You can also use long.TryParse or int.TryParse based on your number, and then use that value in string.Format.

long number;
string str = "123456789";
if (!long.TryParse(str, out number))
{
    //invalid number
}

string formattedStr = String.Format("{0:###-##-####}", number);
Habib
  • 219,104
  • 29
  • 407
  • 436
1

You can use Regex.Replace method

string formatted = Regex.Replace("123456789", @"(.{3})(.{2})(.{4})", "$1-$2-$3");

Given you have not so many digits (or letters), you can use multiple dots.

string formatted = Regex.Replace("123456789", @"(...)(..)(....)", "$1-$2-$3");
Ulugbek Umirov
  • 12,719
  • 3
  • 23
  • 31
0

You can try to print single character

 string.Format("{0}{1}{2}", "123".ToCharArray().Cast<object>().ToArray()) 

Modify this code to support variable length of SSN (if it's necessary - build format string in runtime).

lavrik
  • 1,456
  • 14
  • 25
0

SSN are normally stored in varchar. If so, you can use like this utility method.

public static string FormatSSN(string ssn)
{
    if (String.IsNullOrEmpty(ssn))
        return string.Empty;

    if (ssn.Length != 9)
        return ssn;

    string first3 = ssn.Substring(0, 3);
    string middle2 = ssn.Substring(6, 2);
    string last4 = ssn.Substring(5, 4);

    return string.Format("{0}-{1}-{2}", first3, middle2, last4);
}
Win
  • 61,100
  • 13
  • 102
  • 181