<p>How do I format a number in Java?<br />
What are the &quot;Best Practices&quot;?</p>
<p>Will I need to round a number before I format it?</p>
<blockquote>
<p><code>32.302342342342343</code> =&gt; <code>32.30</code></p>
<p><code>.7323</code> =&gt; <code>0.73</code></p>
</blockquote>
<p>etc.</p>

From
this thread
, there are different ways to do this:
```
```
double r = 5.1234;
System.out.println(r); // r is 5.1234

int decimalPlaces = 2;
BigDecimal bd = new BigDecimal(r);

// setScale is immutable
bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP);
r = bd.doubleValue();

System.out.println(r); // r is 5.12
```
```
```
```
f = (float) (Math.round(n*100.0f)/100.0f);
```
```
```
```
DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
double dd = 100.2397;
double dd2dec = new Double(df2.format(dd)).doubleValue();

// The value of dd2dec will be 100.24
```
```
The
DecimalFormat()
seems to be the most dynamic way to do it, and it is also very easy to understand when reading others code.