wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Formatting doubles in a toString return Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Formatting doubles in a toString return" Watch "Formatting doubles in a toString return" New topic
Author

Formatting doubles in a toString return

S Gregg
Greenhorn

Joined: Oct 13, 2009
Posts: 15
Hey guys,

I'm new here but think I'm going to become a regular visitor now that I started my Java class. I am having trouble with one of my assignments, I have a toString method that is supposed to print out information on a triangle. My problem is I am trying to format the numbers to 2 or 3 decimal places but having some difficulty. Here is my toString method


The call to the toString method looks like this


The length variables as well as the perimeter and area are the ones that are of type double and are the ones I'm trying to round off to 3dp.

Any help is greatly appreciated.
Rahul P Kumar
Ranch Hand

Joined: Sep 26, 2009
Posts: 188
visit this link
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19672
    
  18

Rahul.p Kumar wrote:visit this link

That method is used internally already by the code S Gregg posted; String concatenation already converts all non-Strings using one of the overloaded String.valueOf methods.

S Gregg, check out String.format / java.util.Formatter or java.text.NumberFormat.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38433
    
  23
And welcome to JavaRanch

Agree with Rob; my preference would be to use Rob's first suggestion. That is very closely related to the Formatter methods; I think it simply creates a Formatter object and passes the arguments on to that.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Formatting doubles in a toString return