aspose 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
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply 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: 215
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
Bartender

Joined: Aug 16, 2005
Posts: 12907
    
    3

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 7 API documentation
Scala Notes - My blog about Scala
James Dekker
Ranch Hand

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

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
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: How to set decimals to only 2 digits in Doubles?
 
Similar Threads
TreeCellEditor
help with double
Question on NumberFormat
Objects and Classes
Validating alpha and numeric chars in a form