• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Formatting doubles in a toString return

 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
visit this link
 
Sheriff
Posts: 22781
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.
 
Marshal
Posts: 79153
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Forget Steve. Look at this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic