# Thread: Limiting decimal places in a double

1. Member
Join Date
Mar 2010
Posts
4
Rep Power
0

## Limiting decimal places in a double

When i write in my program

double pi = Math.PI;

This will give me a value of PI accurate to many decimal places, but what if i want to limit this number
lets say to 3 decimal places..
Is there such a method in Java?

(Im not talking here only about the value of Math.PI or Math.E, but about all double values that contain
many decimal places)

2. Member
Join Date
Jan 2010
Posts
37
Rep Power
0

3. Moderator
Join Date
Feb 2009
Location
New Zealand
Posts
4,565
Rep Power
12
@WillRobinson

4. Moderator
Join Date
Feb 2009
Location
New Zealand
Posts
4,565
Rep Power
12
"Decimal places" - indeed even the concept of "decimal" - refers to the string form that numbers often have. It's not quite true, but almost always, when you are talking about "decimal places" you are talking about strings and formatting.

Use the DecimalFormat class. Or java.util.Formatter. The latter class is used with the likes of the String format() method and is very flexible.

5. Agree. Avoid RoseIndia unless you want advice that may or may not be correct.

The question I would like to ask is this: do you truly want to round the number or the display of numbers? Often what matters is the latter, and if that is your case, then you may wish to look into the String.format/Formatter/printf family or DecimalFormat.

Edit: too late! I saw pbrock's first post but not the second. OP, please look at his links for they show the "True Way"™
Last edited by Fubarable; 03-14-2010 at 02:07 AM.

6. Moderator
Join Date
Feb 2009
Location
New Zealand
Posts
4,565
Rep Power
12
I always forget, but Oracle's Tutorial was - long ago in sunnier days - updated to have a "by example" page on Formatting Numeric Print Output. The examples I linked to are good reference material but the tutorial might provide something that is a little less heavy going.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•