File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Formatting doubles in a toString return" Watch "Formatting doubles in a toString return" New topic

Formatting doubles in a toString return

S Gregg

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

Joined: Oct 27, 2005
Posts: 20276

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.

How To Ask Questions How To Answer Questions
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46409
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:
subject: Formatting doubles in a toString return
It's not a secret anymore!