Format a string for phone format

3

I have the following string "49988070405" and I want to format it to "(49) 98807-0405" .

I tried the code:

Convert.ToUInt64("49988070405").ToString(@"\(00\)\ 00000\-0000");

But unsuccessful

    
asked by anonymous 16.03.2018 / 22:18

3 answers

4

You can do this as follows:

long.Parse("49988070405").ToString(@"(00) 00000-0000"); // (49) 98807-0405

Another example, using extensions:

using System;

public static class Program
{
    public static void Main()
    {
        var phoneString = "49988070405";

        Console.WriteLine(phoneString.FormatPhoneNumber()); // (49) 98807-0405

        var phone = 49988070405;

        Console.WriteLine(phone.FormatPhoneNumber()); // (49) 98807-0405
    }

    public static string FormatPhoneNumber(this long number) {
        return number.ToString(@"(00) 00000-0000");
    }

    public static string FormatPhoneNumber(this string number) {
        return long.Parse(number).FormatPhoneNumber();
    }
}

See the examples working in .NET Fiddle.

    
17.03.2018 / 06:00
0

You can do the following, an example:

String.Format("{0:(###) ###-####}", 8005551212);

That results in:

(800) 555-1212
    
16.03.2018 / 22:26
0

You can use the following:

string phone = "49988070405"
string formatted = string.Format("{0:(##) #####-####}", phone);
    
16.03.2018 / 22:48