简体   繁体   中英

Format phone number which starts by 0

I know none of the phone number starts by 0 in USA. In case if someone enters phone number like this 0237858585 I want to format that as (023) 785-8585.

Currently I'm using PhoneNumberFormatted = $"{int.Parse(PhoneNumber):(###) ###-####}"; to format phone number which was not working in the above case. It display as (23) 785-8585

Can someone help on this?

As I said in comment, you need to consider such values as string as converting them to number would loose the leading zeros if it has any.

Assuming that you will have phone number of exact 10 digits you can use following.

var phoneNumber = "0237858585";
var formattedNumber = $"({phoneNumber.Substring(0,3)}) {phoneNumber.Substring(3,3)}-{phoneNumber.Substring(6)}";
Console.WriteLine(formattedNumber);

You can use this logic conditionally, like if the number start with "0" then use this else you can use the normal formatting which you are using currently.

尝试这个 :

String.Format("{0:(0##) ###-####}", 237858585); // Displays (023) 785-8585

When formatting numbers, using "#" will drop leading zeros. If you want to keep leading zeros, use "0" as the place holder for leading digits that could be zero.

NOTE: The "0" means display the digit, if there is one, otherwise display "0". It does not mean place a literal "0" at the start of the string.

var PhoneNumber = "0237858585";
Console.WriteLine($"{int.Parse(PhoneNumber):(0##) ###-####}");
//Output will be "(023) 785-8585"

PhoneNumber = "237858585";
Console.WriteLine($"{int.Parse(PhoneNumber):(0##) ###-####}");
//Output will be "(023) 785-8585"

PhoneNumber = "1237858585";
Console.WriteLine($"{int.Parse(PhoneNumber):(0##) ###-####}");
//Output will be "(123) 785-8585"

PhoneNumber = "1237858585";
Console.WriteLine($"{int.Parse(PhoneNumber):(000) 000-0000}");
//Output will be "(123) 785-8585"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM