How do format a phone number as a String in Java?
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"));
To get your desired output:
long phoneFmt = 123456789L;
//get a 12 digits String, filling with left '0' (on the prefix)
DecimalFormat phoneDecimalFmt = new DecimalFormat("0000000000");
String phoneRawString= phoneDecimalFmt.format(phoneFmt);
java.text.MessageFormat phoneMsgFmt=new java.text.MessageFormat("({0})-{1}-{2}");
//suposing a grouping of 3-3-4
String[] phoneNumArr={phoneRawString.substring(0, 3),
phoneRawString.substring(3,6),
phoneRawString.substring(6)};
System.out.println(phoneMsgFmt.format(phoneNumArr));
The result at the Console looks like this:
(012)-345-6789
For storing phone numbers, you should consider using a data type other than numbers.
The easiest way to do this is by using the built in MaskFormatter in the javax.swing.text library.
You can do something like this :
import javax.swing.text.MaskFormatter;
String phoneMask= "###-###-####";
String phoneNumber= "123423452345";
MaskFormatter maskFormatter= new MaskFormatter(phoneMask);
maskFormatter.setValueContainsLiteralCharacters(false);
maskFormatter.valueToString(phoneNumber) ;
If you really need the right way then you can use Google's recently open sourced libphonenumber