Format("{0:(###)###-"+new string('#',phoneNumber. Length-6)+"}", Convert. ToInt64(phoneNumber) ); else result = phoneNumber; return result; Cheers.
To format phone numbers in the US, Canada, and other NANP (North American Numbering Plan) countries, enclose the area code in parentheses followed by a nonbreaking space, and then hyphenate the three-digit exchange code with the four-digit number.
It is not unusual to see [Phone] and [DataType(DataType. PhoneNumber)] used interchangeably in C# code, and since the first usage is shorter many developers turn to it as a matter of habit.
String input = "1234567890" ; String number = input. replaceFirst( "(\\d{3})(\\d{3})(\\d+)" , "($1) $2-$3" );
Please note, this answer works with numeric data types (int, long). If you are starting with a string, you'll need to convert it to a number first. Also, please take into account that you'll need to validate that the initial string is at least 10 characters in length.
From a good page full of examples:
String.Format("{0:(###) ###-####}", 8005551212);
This will output "(800) 555-1212".
Although a regex may work even better, keep in mind the old programming quote:
Some people, when confronted with a problem, think “I know, I’ll use regular expressions.” Now they have two problems.
--Jamie Zawinski, in comp.lang.emacs
I prefer to use regular expressions:
Regex.Replace("1112224444", @"(\d{3})(\d{3})(\d{4})", "$1-$2-$3");
You'll need to break it into substrings. While you could do that without any extra variables, it wouldn't be particularly nice. Here's one potential solution:
string phone = i["MyPhone"].ToString();
string area = phone.Substring(0, 3);
string major = phone.Substring(3, 3);
string minor = phone.Substring(6);
string formatted = string.Format("{0}-{1}-{2}", area, major, minor);
I suggest this as a clean solution for US numbers.
public static string PhoneNumber(string value)
{
if (string.IsNullOrEmpty(value)) return string.Empty;
value = new System.Text.RegularExpressions.Regex(@"\D")
.Replace(value, string.Empty);
value = value.TrimStart('1');
if (value.Length == 7)
return Convert.ToInt64(value).ToString("###-####");
if (value.Length == 10)
return Convert.ToInt64(value).ToString("###-###-####");
if (value.Length > 10)
return Convert.ToInt64(value)
.ToString("###-###-#### " + new String('#', (value.Length - 10)));
return value;
}
As far as I know you can't do this with string.Format ... you would have to handle this yourself. You could just strip out all non-numeric characters and then do something like:
string.Format("({0}) {1}-{2}",
phoneNumber.Substring(0, 3),
phoneNumber.Substring(3, 3),
phoneNumber.Substring(6));
This assumes the data has been entered correctly, which you could use regular expressions to validate.
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