• Post Reply Bookmark Topic Watch Topic
  • New Topic

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

 
Ranch Hand
Posts: 672
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Sheriff
Posts: 4313
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Jessica Sant
Sheriff
Posts: 4313
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 1879
MySQL Database Suse
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you need to something a little more crude than use the Format class. Something like:

Jamie
 
Bruce Jin
Ranch Hand
Posts: 672
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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"
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!