File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes How to format a 10-digit into a phone number? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "How to format a 10-digit into a phone number?" Watch "How to format a 10-digit into a phone number?" New topic
Author

How to format a 10-digit into a phone number?

Bruce Jin
Ranch Hand

Joined: Sep 20, 2001
Posts: 666
DecimalFormat myFormatter = new DecimalFormat("( ) - ");
String output = myFormatter.format(1234567890);
System.out.println("result=" + output);
The output is
( ) - 1234567890
How to make it (123) 456-7890
Thanks


BJ - SCJP and SCWCD
We love Java programming. It is contagious, very cool, and lot of fun. - Peter Coad, Java Design

Crazy Bikes created by m-Power
Jessica Sant
Sheriff

Joined: Oct 17, 2001
Posts: 4313

Check out the API for java.text.DecimalFormat.
You need to use the Special Character Patterns they define to tell instruct the DecimalFormatter where to put the digits in relation to the "( ) -"

[ June 03, 2002: Message edited by: Jessica Sant ]

- Jess
Blog:KnitClimbJava | Twitter: jsant | Ravelry: wingedsheep
Jessica Sant
Sheriff

Joined: Oct 17, 2001
Posts: 4313

hmmmm after looking at that class... I don't know if it can be used to do what you need it to. You might be better off converting the number to a StringBuffer and creating your own class to manipluate it.
Jamie Robertson
Ranch Hand

Joined: Jul 09, 2001
Posts: 1879

I think you need to something a little more crude than use the Format class. Something like:

Jamie
Bruce Jin
Ranch Hand

Joined: Sep 20, 2001
Posts: 666
Thanks for the replies.
I am a little surprised that Java format class can’t do this. Other languages such as RPG, COBOL can do this easily.
David Koontz
Greenhorn

Joined: Oct 08, 2003
Posts: 14
Just submitted a class TelephoneNumber to do phone formating to
SourceForge
http://sourceforge.net/snippet/detail.php?type=snippet&id=101225
David
-- snip --
The TelephoneNumber class represents a US telephone number.
This class contains many constructors for various uses. It then stores the telephone number internally in seperate codes (area code, exchange, etc.). This encourages
use of the format method to output the telephone number in any style the programmer wishes.
[needs i18n work]
Example usage:
long number = 8005551212L;
TelephoneNumber phone = new TelephoneNumber(number);
StringBuffer msg = new StringBuffer("Call me at ");
msg.append(phone.format());
// msg is now "Call me at (800) 555-1212"
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: How to format a 10-digit into a phone number?
 
Similar Threads
JLabel
Problem with Conversion
Format number
Casting
thousands-separators