This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Numerics to a String

 
Rick Rodriguez
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 168
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 241
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The toString() method also works.
 
Roy Tock
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rick, if you just need to truncate, then casting the double to an int will do it.
Try this:

It prints 2.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic