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

styfle picture styfle · Feb 25, 2011 · Viewed 101.7k times · Source

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?

Answer

hhbarriuso picture hhbarriuso · Feb 25, 2011

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"));