简体   繁体   English

格式化以0开头的电话号码

[英]Format phone number which starts by 0

I know none of the phone number starts by 0 in USA. 我知道美国的电话号码都不以0开头。 In case if someone enters phone number like this 0237858585 I want to format that as (023) 785-8585. 如果有人输入像这样的电话号码0237858585,我想将其格式化为(023)785-8585。

Currently I'm using PhoneNumberFormatted = $"{int.Parse(PhoneNumber):(###) ###-####}"; 当前,我正在使用PhoneNumberFormatted = $"{int.Parse(PhoneNumber):(###) ###-####}"; to format phone number which was not working in the above case. 格式化在上述情况下不起作用的电话号码。 It display as (23) 785-8585 显示为(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. 假设您的电话号码精确到10位数字,则可以使用以下代码。

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. 您可以有条件地使用此逻辑,例如,如果数字以“ 0”开头,则可以使用此逻辑,否则您可以使用当前使用的常规格式。

尝试这个 :

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. 如果要保留前导零,请将“ 0”用作可能为零的前导数字的占位符。

NOTE: The "0" means display the digit, if there is one, otherwise display "0". 注意:“ 0”表示显示数字,如果有一位,则显示“ 0”。 It does not mean place a literal "0" at the start of the string. 这并不意味着在字符串的开头放置文字“ 0”。

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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