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?
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))
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With