• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to set decimals to only 2 digits in Doubles?

 
James Dekker
Ranch Hand
Posts: 221
  • Mark post as helpful
  • send pies
  • 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...
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15480
43
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • 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: 221
  • Mark post as helpful
  • send pies
  • 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!
 
Rob Spoor
Sheriff
Pie
Posts: 20659
64
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • 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:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic