This example will show how to format a phone number with java's String.format and Google's phone number handling library.
@Test public void format_phone_number_java () { String rawNumber = "1234567890"; String formattedNumber = String.format("(%s) %s-%s", rawNumber.substring(0, 3), rawNumber.substring(3, 6), rawNumber.substring(6, 10)); assertEquals("(123) 456-7890", formattedNumber); }
@Test public void format_phone_number_google_libphonenumber () throws NumberParseException { PhoneNumber phoneNumber = new PhoneNumber(); phoneNumber.setCountryCode(1); phoneNumber.setExtension("12345"); phoneNumber.setNationalNumber(1234567890); PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance(); String formattedPhoneNumber = phoneUtil.format(phoneNumber, PhoneNumberFormat.NATIONAL); assertEquals("(123) 456-7890 ext. 12345", formattedPhoneNumber); }