File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes How to set decimals to only 2 digits in Doubles? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to set decimals to only 2 digits in Doubles?" Watch "How to set decimals to only 2 digits in Doubles?" New topic
Author

How to set decimals to only 2 digits in Doubles?

James Dekker
Ranch Hand

Joined: Dec 09, 2006
Posts: 219
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

Joined: Aug 16, 2005
Posts: 14435
    
  23

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.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
James Dekker
Ranch Hand

Joined: Dec 09, 2006
Posts: 219
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

Joined: Oct 27, 2005
Posts: 19794
    
  20

You can use the static String.format method to create a String with the same type of arguments to System.out.printf:


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to set decimals to only 2 digits in Doubles?