Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format string phone number MVC Razor without parsing to decimal

I am trying to format phone numbers that are being looped in from my viewModel like so: (###) ###-#### without having to parse the string to a decimal.

This method gives a Formatting is specified, but argument is not IFormattable error:

@foreach (var client in Model.Clients)
{
    <td>@String.Format("{0:(###) ###-####}", client.TelephoneNumber)</td>
}

So, I would need to parse to a decimal:

@foreach (var client in Model.Clients)
{
    <td>@String.Format("{0:(###) ###-####}", Decimal.Parse(client.TelephoneNumber))</td>
}

But there is no guarantee that the numbers being looped in will be just digits so most likely at least one parse attempt will fail.

Is there a way to achieve this formatting without the need to Parse to a decimal?

like image 203
cfly24 Avatar asked Sep 22 '15 21:09

cfly24


2 Answers

If your TelephoneNumber is a string you always can use substrings to format number. It's not so clean, but you don't need any separate libraries and convert to decimal:

        @String.Format("({0}) {1}-{2}"
            , client.TelephoneNumber.Substring(0, 3)
            , client.TelephoneNumber.Substring(3, 3)
            , client.TelephoneNumber.Substring(6, client.TelephoneNumber.Length - 6))
like image 116
teo van kot Avatar answered Sep 23 '22 02:09

teo van kot


Try this, you may put it in a static function somewhere for repeated use.

var match = Regex.Match("1231231234", @"(\d{3})(\d{3})(\d{4})");
Console.WriteLine( "(" + match.Groups[1] + ") " + match.Groups[2] + "-" + match.Groups[3]);
like image 38
Ghasan غسان Avatar answered Sep 19 '22 02:09

Ghasan غسان