Formatting Phone Number in Android

2019-07-31 18:27发布

问题:

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.

回答1:

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;
    }


回答2:

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.



回答3:

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:

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