Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android: how do I format number as phone with parentheses

I have a number that I need to format as a telephone number. If I do

 PhoneNumberUtils.formatNumber(numStr);

Then I get

888-555-1234

But what I need to get is

(888) 555-1234

How do I get the second one? Is there a standard android way?

like image 249
user3093402 Avatar asked Jan 21 '14 22:01

user3093402


People also ask

How do you write parentheses in a phone number?

To format phone numbers in the US, Canada, and other NANP (North American Numbering Plan) countries, enclose the area code in parentheses followed by a nonbreaking space, and then hyphenate the three-digit exchange code with the four-digit number.

How do you format a phone number with an extension?

Write out "extension" with the extension number beside it or simply write "ext." with the extension number beside it on the same line as the phone number you are listing. It should look like either (555) 555-5555 extension 5 or (555) 555-5555 ext. 5.


2 Answers

Don't know if you found what you were looking for, but I ended up writing a little method that takes the length of a string (since the phone numbers I get come from a web service and can be a variety of formats). I believe it should work (so far all my test cases have been with the first two options -- haven't tested the other two yet).

public static String FormatStringAsPhoneNumber(String input) {
    String output;
    switch (input.length()) {
        case 7:
            output = String.format("%s-%s", input.substring(0,3), input.substring(3,7));
            break;
        case 10:
            output = String.format("(%s) %s-%s", input.substring(0,3), input.substring(3,6), input.substring(6,10));
            break;
        case 11:
            output = String.format("%s (%s) %s-%s", input.substring(0,1) ,input.substring(1,4), input.substring(4,7), input.substring(7,11));
            break;
        case 12:
            output = String.format("+%s (%s) %s-%s", input.substring(0,2) ,input.substring(2,5), input.substring(5,8), input.substring(8,12));
            break;
        default:
            return null;
    }
    return output;
}
like image 97
Sal Aldana Avatar answered Sep 17 '22 12:09

Sal Aldana


If you have the String "888-555-1234" - by using PhoneNumberUtils.formatNumber(numStr); you can simply do this:

String numStr = "888-555-1234";

numStr = "(" + numStr.substring(0,3) + ") " + numStr.substring(4);

System.out.print(numStr); // (888) 555-1234

However, this is hard coded. You would need to make sure the String had a full 10 digits before doing so.

like image 40
Michael Yaworski Avatar answered Sep 19 '22 12:09

Michael Yaworski