This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
The moose likes Java in General and the fly likes trying to restrict decimal places in double Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "trying to restrict decimal places in double" Watch "trying to restrict decimal places in double" New topic
Author

trying to restrict decimal places in double

Bob Backlund
Ranch Hand

Joined: Jun 05, 2003
Posts: 51
Hi

Just a quick one. Anyone know how to restrict the number of decimal places in a doouble value to 2?

I've had a look around and seen a few answer with silly caluculations (divide by 100 * by itself etc...) but none of them seem to work. All i want to do is reduce the decimal places for a value

so for example: 10.714285714285714% becomes 10.71%


thanx


Cheers!
Nigel Browne
Ranch Hand

Joined: May 15, 2001
Posts: 673
Have a look at the API for the DecimalFormat class.
PVH
Greenhorn

Joined: Jun 13, 2003
Posts: 5
As the previous post suggests, just use the DecimalFormat class in the java.text package. Something like this should work:

Double d = (65.28262);
DecimalFormat df = new DecimalFormat("0.00");
df.format(d);
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
If what you want to do is to obtain a textual representation of the value, with two decimal places, DecimalFormat is indeed the way to go.

If what you want to do is to perform calculations using only two decimal places, then you should not be using floating-point arithmetic. Instead, you should do integer calculations, using "hundredths" (if you're doing currency, call them "cents", "pence" etc.).


Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: trying to restrict decimal places in double