Formatting Phone Number in Android

2019-07-31 18:22发布

I tried the following code to format phone number in android:-

public static String formatPhoneNumber(String number){

        return PhoneNumberUtils.formatNumber(number);
    }

I am passing "19253951646" to the function.. It returns the text in the format 1-925-395-1646. I want the result in the format 1(925)395-1646. Any help would be highly apprciated.

3条回答
闹够了就滚
2楼-- · 2019-07-31 18:26

1-925-395-1646

number have international USA format. If you want custom format, you can parse number manually and format him.

So, you can try insert +1 before number.

A proof on my iPhone:

enter image description here

Also try that: How to format a phone number using PhoneNumberUtils?

查看更多
狗以群分
3楼-- · 2019-07-31 18:41

Android SDKs PhoneNumberUtils has more or less adequate phone number formatting utils but sometimes it might not be enough for special needs.

Try out alternative library libphonenumber described as "Google's common Java, C++ and JavaScript library for parsing, formatting, storing and validating international phone numbers. The Java version is optimized for running on smartphones, and is used by the Android framework since 4.0 (Ice Cream Sandwich)."

The library has different phone number formatting options.

查看更多
放我归山
4楼-- · 2019-07-31 18:49

Wrote my own function to format the number.

public static String formatPhoneNumber(String number){  
        number  =   number.substring(0, number.length()-4) + "-" + number.substring(number.length()-4, number.length());
        number  =   number.substring(0,number.length()-8)+")"+number.substring(number.length()-8,number.length());
        number  =   number.substring(0, number.length()-12)+"("+number.substring(number.length()-12, number.length());
        return number;
    }
查看更多
登录 后发表回答