• 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

How to set decimals to only 2 digits in Doubles?

 
Ranch Hand
Posts: 231
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello,

I am have the following method (pseudo code) which sums up totals:



Sometimes, my method returns values such as this:

25.00
125.00024
131.35001
33.0

How to I set up it so it only shows two digits, as follows:

25.00
125.00
131.35
33.00

Thank you for taking the time to read this...
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
First of all, is there a reason why you use Double objects instead of the primitive type double? Also note that floating-point data types are not suitable for storing amounts of money in real-world programs because floating-point numbers have limited precision, you can get roundoff errors which are not acceptable when dealing with money.

There are several ways to print numbers with nice formatting. One way is to use System.out.printf(). For example:


If you don't want to print it, but just return the result formatted in a string, use String.format("%.2f", number); instead (that returns a String).

Another, slightly more cumbersome way, is to use class java.text.NumberFormat.
 
James Dekker
Ranch Hand
Posts: 231
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Jesper,

In my situation I was going to display in inside a JSP...

I ended up using the DecimalFormat class:



Thanks for the response!
 
Sheriff
Posts: 22783
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
You can use the static String.format method to create a String with the same type of arguments to System.out.printf:
 
Let's get him boys! We'll make him read this tiny ad!
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic