How to format a phone number using PhoneNumberUtils?

Android

Android Problem Overview


How can I format a phone number using PhoneNumberUtils?

E.g.: 1234567890(123) 456-7890

Android Solutions


Solution 1 - Android

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.

Solution 2 - Android

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

Solution 3 - Android

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

Solution 4 - Android

It looks like this library from Google might be a better solution for doing customized formatting in Android.

API docs: https://github.com/googlei18n/libphonenumber/blob/master/README.md

Solution 5 - Android

2020- November

Following worked for me for all version of OS:

PhoneNumberUtils.formatNumber(yourStringPhone,Locale.getDefault().getCountry());

Solution 6 - Android

Standalone solution for format raw phone number, if you don`t know your country and need support on pre-lollipop.

fun formatNumberCompat(rawPhone: String?, countryIso: String = ""): String {
    if (rawPhone == null) return ""

    var countryName = countryIso
    if (countryName.isBlank()) {
        countryName = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Resources.getSystem().configuration.locales[0].country
        } else {
            Resources.getSystem().configuration.locale.country
        }
    }

    return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        PhoneNumberUtils.formatNumber(rawPhone)
    } else {
        PhoneNumberUtils.formatNumber(rawPhone, countryName)
    }
}

Solution 7 - Android

2020 working sulotion:

TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

String countryIso = telephonyManager.getNetworkCountryIso().toUpperCase();				//important!!

phoneNumberTextView.setText(PhoneNumberUtils.formatNumber("3473214567", countryIso));

Solution 8 - Android

We can easily do this by:

val tm = act.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager?
val formattedPhoneNumber= PhoneNumberUtils.formatNumber(phone, tm?.simCountryIso?.toUpperCase())

here, tm?.simCountryIso?.toUpperCase() returns iso code, "in" in my case and we used toUpperCase() to convert it into "IN"

you can also use networkCountryIso instead of simCountryIso.

From doc:

getNetworkCountryIso(): Returns the ISO-3166-1 alpha-2 country code equivalent of the MCC (Mobile Country Code) of the current registered operator or the cell nearby, if available.

getSimCountryIso(): Returns the ISO-3166-1 alpha-2 country code equivalent for the SIM provider's country code.

you can also pass direct iso code, for example:

PhoneNumberUtils.formatNumber("2025550739", "US") // output: (202) 555-0739

Check the list of iso codes.

Solution 9 - Android

In order to define your custom formatting pattern, you have to use formatByPattern method with your instance of Phonemetadata.NumberFormat

        private fun getFormattedNumber(numberString: String): String? {
        val phoneNumberUtil = PhoneNumberUtil.getInstance()
        val numberFormat = Phonemetadata.NumberFormat().apply {
            pattern = "(\\d{3})(\\d{3})(\\d+)"
            format = "($1) $2-$3"//your custom formatting
        }
        try {
            val phoneNumberPN: Phonenumber.PhoneNumber =
                phoneNumberUtil.parse(numberString, Locale.US.country)
            
            return phoneNumberUtil.formatByPattern(
                phoneNumberPN,
                PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL,
                listOf(numberFormat)
            )//returns the expected result
        } catch (e: NumberParseException) {
            e.printStackTrace()
        }
        return null

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBytecodeView Question on Stackoverflow
Solution 1 - AndroidSven VikingView Answer on Stackoverflow
Solution 2 - AndroidsobelitoView Answer on Stackoverflow
Solution 3 - AndroidMauricio SartoriView Answer on Stackoverflow
Solution 4 - AndroidNorman HView Answer on Stackoverflow
Solution 5 - AndroidRajeev JayaswalView Answer on Stackoverflow
Solution 6 - AndroidwhalemareView Answer on Stackoverflow
Solution 7 - AndroidSam ChenView Answer on Stackoverflow
Solution 8 - AndroidSuraj VaishnavView Answer on Stackoverflow
Solution 9 - AndroidPavlo ZoriaView Answer on Stackoverflow