Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do format a phone number as a String in Java?

I have been storing phone numbers as longs and I would like to simply add hyphens when printing the phone number as a string.

I tried using DecimalFormat but that doesn't like the hyphen. Probably because it is meant for formatting decimal numbers and not longs.

long phoneFmt = 123456789L; DecimalFormat phoneFmt = new DecimalFormat("###-###-####"); System.out.println(phoneFmt.format(phoneNum)); //doesn't work as I had hoped 

Ideally, I would like to have parenthesis on the area code too.

new DecimalFormat("(###)-###-####"); 

What is the correct way to do this?

like image 436
styfle Avatar asked Feb 25 '11 07:02

styfle


People also ask

How do you format 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.

What is %d and %s in Java?

%d means number. %0nd means zero-padded number with a length. You build n by subtraction in your example. %s is a string. Your format string ends up being this: "%03d%s", 0, "Apple"

What is string format () in Java?

In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string.


1 Answers

You can use String.replaceFirst with regex method like

    long phoneNum = 123456789L;     System.out.println(String.valueOf(phoneNum).replaceFirst("(\\d{3})(\\d{3})(\\d+)", "($1)-$2-$3")); 
like image 195
hhbarriuso Avatar answered Sep 18 '22 23:09

hhbarriuso