# Limiting number of decimal places

Page 1 of 1

## 2 Replies - 11183 Views - Last Post: 13 March 2010 - 04:01 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=161785&amp;s=d4d64588204f4a4720b73f39846fcc26&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 darek9576

• D.I.C Lover

Reputation: 203
• Posts: 1,731
• Joined: 13-March 10

# Limiting number of decimal places

Posted 13 March 2010 - 03:55 PM

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)
Is This A Good Question/Topic? 0

## Replies To: Limiting number of decimal places

### #2 zim1985

• Grand Inquisitor

Reputation: 75
• Posts: 568
• Joined: 19-February 10

## Re: Limiting number of decimal places

Posted 13 March 2010 - 04:00 PM

Use the numberformat class

```import java.text.NumberFormat;

NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);

public static void main(String[] args)
{
double pi = Math.PI;
System.out.println(nf.format(pi));
}

```

That will format Pi to 2 decimal places.

Check it out: http://java.sun.com/...mberFormat.html

I'd just like to point out that you could have just used NumberFormat.getInstance() for an even more "all-purpose" formatter.

There are also a gamut of other ways to do rounding, I just like the Format classes.

This post has been edited by zim1985: 13 March 2010 - 04:09 PM

### #3 macosxnerd101

• Games, Graphs, and Auctions

Reputation: 12298
• Posts: 45,399
• Joined: 27-December 08

## Re: Limiting number of decimal places

Posted 13 March 2010 - 04:01 PM

Yes- you can use the System.out.printf() or the String.format() methods, which work basically the same way. Here is a printf() example for three decimal places:
```System.out.printf("Pi: %.3f", Math.PI);

```

So where the %.3f is, Math.PI will be placed there instead rounded to 3 decimal places. Note that you can specify as many values using printf() as you want (so long as they don't exceed memory), and you can use other types like ints, Strings, etc., not just floating-point numbers (double, float).

For more information on String formatting, you can check out these tutorials:
http://www.java2s.co...tObjectargs.htm
http://java.sun.com/...ter.html#syntax