jQuery in Action, 3rd edition
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: 221
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: 14958
    
  26

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: 221
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: 20080
    
  30

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 - OCEJPAD 6
How To Ask Questions How To Answer Questions
 
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
 
subject: How to set decimals to only 2 digits in Doubles?
 
It's not a secret anymore!