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?
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.
%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"
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.
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With