By

Formatting Phone Numbers in Java and Android

I needed to format numbers nicely while storing them as a raw string in my database, so I need to turn
0433333333 into 0433 333 333 and 0262195555 into (02) 6219 5555

I couldn’t find something that did this as nicely as I hoped, but this does the job if you know what format your numbers will be as I do (They are all Australian)

My searching didn’t turn up a string mask formatter apart from one in Swing (and I sure don’t want to be importing THAT into an Android project!) so splitting and adding spaces, brackets etc. using  .substring(…) was the nicest way I could think of without writing a whole library.

Make sure the number is a raw numeric string before converting:-

public final class PhoneNumberUtils {

    private PhoneNumberUtils() {

    }

    public static String stripAustralianNumber(String number) {
        if (StringUtils.isEmpty(number)) {
            return null;
        }
        number = stripCountryCode(number);
        // now strip non-numeric
        return number.replaceAll("[^\\d]", "");
    }

    private static String stripCountryCode(String string) {
        if (string.startsWith("+61")) {
            return string.replace("+61", "0");
        } else if (string.startsWith("+")) {
           //handle invalid numbers
        }
        return string;
    }

now the method to format your phone numbers – as noted, this is for Australian numbers, but you can change it easy enough.

 public static String prettyPhoneNumber(String phoneNumber) {

        phoneNumber = stripAustralianNumber(phoneNumber);
        StringBuilder sb = new StringBuilder();

        if (phoneNumber.startsWith("04") || phoneNumber.startsWith("1800")
                || phoneNumber.startsWith("1300")) {
            sb.append(phoneNumber.substring(0, 4)).append(" ")
                    .append(phoneNumber.substring(4, 7)).append(" ")
                    .append(phoneNumber.substring(7, phoneNumber.length()));
        } else if (phoneNumber.length() == 6 && phoneNumber.startsWith("13")) {
            sb.append(phoneNumber.substring(0, 2)).append(" ")
                    .append(phoneNumber.substring(2, 4)).append(" ")
                    .append(phoneNumber.substring(4, phoneNumber.length()));
        } else if (phoneNumber.startsWith("0")) {
            sb.append("(").append(phoneNumber.substring(0, 2)).append(") ")
                    .append(phoneNumber.substring(2, 6)).append(" ")
                    .append(phoneNumber.substring(6, phoneNumber.length()));
        } else {
            sb.append(phoneNumber.substring(0, 4)).append(" ")
                    .append(phoneNumber.substring(4, phoneNumber.length()));
        }

        return sb.toString();
    }
}

I may look at creating a library later on that will do things in a nicer way.