Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I Format A String Like A Number in .NET?

If I had a phone number like this

string phone = "6365555796";

Which I store with only numeric characters in my database (as a string), is it possible to output the number like this:

"636-555-5796"

Similar to how I could if I were using a number:

long phone = 6365555796;
string output = phone.ToString("000-000-0000");

I've tried searching and all I could find online were numeric formatting documents.

The reason I ask is because I think it would be an interesting idea to be able to store only the numeric values in the DB and allow for different formatting using a Constant string value to dictate how my phone numbers are formatted. Or am I better off using a number for this?

EDIT: The question is to format a string that contains numbers, not a number itself.

like image 960
Dan Herbert Avatar asked Nov 29 '22 12:11

Dan Herbert


1 Answers

Best I can think of without having to convert to a long/number and so it fits one line is:

string number = "1234567890";
string formattedNumber = string.Format("{0}-{1}-{2}", number.Substring(0,3), number.Substring(3,3), number.Substring(6));
like image 90
Esteban Brenes Avatar answered Dec 09 '22 17:12

Esteban Brenes