How to format a phone number using PhoneNumberUtils?

At its most basic:

String formattedNumber = PhoneNumberUtils.formatNumber(unformattedNumber);

This will automatically format the number according to the rules for the country the number is from.

You can also format Editable text in-place using:

PhoneNumberUtils.formatNumber(Editable text, int defaultFormattingType);

Take a look at PhoneNumberUtils for more options.


formatNumber got deprecated on LOLLIPOP, after that you need to add the locale as an extra argument.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  return PhoneNumberUtils.formatNumber(yourStringPhone,Locale.getDefault().getCountry());
} else {
//Deprecated method
  return PhoneNumberUtils.formatNumber(yourStringPhone); 
}

I opted to use google's version (https://github.com/googlei18n/libphonenumber) because then the min SDK can be lower (I think it isn't in Android SDK until 21).

Use is something like this:

PhoneNumberUtil pnu = PhoneNumberUtil.getInstance();
Phonenumber.PhoneNumber pn = pnu.parse("1234567890", "US");
String pnE164 = pnu.format(pn, PhoneNumberUtil.PhoneNumberFormat.E164);

In Android Studio one need add this to dependencies in build.gradle:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    ...
    compile 'com.googlecode.libphonenumber:libphonenumber:7.2.2'
}

Tags:

Android