This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Numerics to a String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Numerics to a String" Watch "Numerics to a String" New topic
Author

Numerics to a String

Rick Rodriguez
Ranch Hand

Joined: Jun 02, 2001
Posts: 44
Anyone,
I know that there are ways/methods that convert a "string" to a "numeric/double/int/etc.", however is there a way to convert a numberic to a string?
The reason that I ask is because I am wanting to "truncate" the value of a double variable. Unlike C/C++, I cannot use "precision" with some type of conversion specifier to do this.
I was thinking about converting the double to a string and outputting only the digits that I want displayed, in effect, truncating the variable's value.
Any feedback would be welcomed. Thanks in advance.
Manju Jain
Ranch Hand

Joined: Feb 08, 2001
Posts: 168
Try valueOf method in String class [ it gives string representation of int , float etc. ] Then, use the subString method to extract the value upto a point you desire.
Hope this helps.
jytsika
Art Metzer
Ranch Hand

Joined: Oct 31, 2000
Posts: 241
Hi, Rick.
I'd recommend that you investigate java.text.DecimalFormat. You can use this class to specify how you'd like your double to be displayed. DecimalFormat's format() method requires that not only the double, but also a StringBuffer and FieldPosition be passed.
To wit:

This code returns

Good luck, Rick.
Art
Lucas Richardson
Ranch Hand

Joined: Jul 08, 2001
Posts: 32
The toString() method also works.
Roy Tock
Ranch Hand

Joined: Jul 16, 2001
Posts: 83
Rick, if you just need to truncate, then casting the double to an int will do it.
Try this:

It prints 2.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Numerics to a String