65

How can I format a phone number using PhoneNumberUtils?

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

Octavian Helm
  • 39,405
  • 19
  • 98
  • 102
Bytecode
  • 6,551
  • 16
  • 54
  • 101

9 Answers9

86

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.

Octavian Helm
  • 39,405
  • 19
  • 98
  • 102
Sven Viking
  • 2,660
  • 21
  • 34
  • instead of 1234567890 → (123) 456-7890 I'm getting: – Brill Pappin Jan 29 '13 at 16:46
  • 1
    While the answer is correct I think the actually correct answer for this question is that the formatting is NOT customizable enough unless you want to write your own implementation. :-( STPhoneFormatter in CocoaPods for iOS development is a pretty slick library to handle this over there. No such joy for Android. :-/ – Norman H Dec 18 '13 at 21:59
  • 1
    @Sven Viking i want to formatted number convert in unformstted number like.. `555-4 to 5554` any solution..? – Gorgeous_DroidVirus Apr 05 '14 at 07:41
  • 7
    [PhoneNumberUtils.formatNumber(String source)](http://developer.android.com/reference/android/telephony/PhoneNumberUtils.html#formatNumber(java.lang.String)) is deprecated in Lollipop, one need to use [PhoneNumberUtils.formatNumber (String phoneNumber, String defaultCountryIso)](http://developer.android.com/reference/android/telephony/PhoneNumberUtils.html#formatNumber(java.lang.String,java.lang.String)) – blizzard Feb 03 '15 at 15:56
  • 1
    `PhoneNumberUtils.formatNumber(Editable text, int defaultFormattingType);` What is `defaultFormattingType` here ? – Azim Ansari Jul 23 '15 at 07:04
  • This method available from api 21, how can i format a number in US below 21 ?. – Rohit Bandil Apr 15 '16 at 09:19
  • Ohh the same method is working on 19 also, i wondered why it is working? – Rohit Bandil Apr 18 '16 at 05:08
29

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'
}
sobelito
  • 1,525
  • 17
  • 13
25

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); 
}
Mauricio Sartori
  • 2,533
  • 6
  • 26
  • 28
  • I tried this but phone number doesn't get formatted on mobile device where as it's working properly on tablet, tablet shows formatted number. – musica Jun 21 '17 at 09:12
  • 1
    I am in India and Locale.getDefault().getCountry() gives me "US". Ok, that's not an issue but number does not gets formatted. It returns 10/11 digit number as is. And with deprecated method, it returns formatted. – pratik03 Jul 24 '17 at 07:19
  • 2
    getCountry() returns "" for me – Tyler Oct 19 '17 at 19:25
  • Worked in USA for me. – M A F Nov 11 '20 at 21:38
8

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

Norman H
  • 2,248
  • 24
  • 27
6

2020- November

Following worked for me for all version of OS:

PhoneNumberUtils.formatNumber(yourStringPhone,Locale.getDefault().getCountry());
Rajeev Jayaswal
  • 1,423
  • 1
  • 20
  • 22
1

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)
    }
}
whalemare
  • 1,107
  • 1
  • 13
  • 30
1

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
Pavlo Zoria
  • 666
  • 7
  • 7
0

2020 working sulotion:

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

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

phoneNumberTextView.setText(PhoneNumberUtils.formatNumber("3473214567", countryIso));
Sam Chen
  • 7,597
  • 2
  • 40
  • 73
0

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.

Suraj Vaishnav
  • 7,777
  • 4
  • 43
  • 46