# Round a double or float number to 2 decimal places in Java

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Aug 7, 2022, updated Nov 26, 2022. Topics: Java.
Canonical URL: https://attacomsian.com/blog/java-round-double-float

> A quick guide to learning about different ways to format a double or float number to two decimal places in Java.

There are multiple ways to round a `double` or `float` value into 2 decimal places in Java. You can use one of the following methods:

1. The `DecimalFormat` class
2. The `BigDecimal` class
3. The `String.format()` method
4. The `Math.round()` method

> **Note:** If you are formatting a currency, always use the `BigDecimal` class. For general display purposes, use the `DecimalFormat` class.

## `DecimalFormat` class

The `DecimalFormat` class can be used to round a double or floating point value to 2 decimal places, as shown below:

```java
double price = 19.5475;

DecimalFormat df = new DecimalFormat("0.00");
System.out.println("Price: " + df.format(price));
// Price: 19.55
```

The default round mode of `DecimalFormat` is `RoundingMode.HALF_EVEN`. You can use the `setRoundingMode()` method to change rounding mode:

```java
double price = 19.5475;
DecimalFormat df = new DecimalFormat("0.00");

// RoundingMode.UP
df.setRoundingMode(RoundingMode.UP);
System.out.println("Price: " + df.format(price)); 
// Price: 19.55

// RoundingMode.DOWN
df.setRoundingMode(RoundingMode.DOWN);
System.out.println("Price: " + df.format(price)); 
// Price: 19.54
```

## `BigDecimal` class

You can also convert the `double` or `float` value to a `BigDecimal` object and then use `setScale()` to set the scale and rounding mode:

```java
double price = 19.5475;

BigDecimal bd = new BigDecimal(Double.toString(price));
System.out.println("Price: " + bd.setScale(2, RoundingMode.HALF_EVEN)); 
// Price: 19.55

// RoundingMode.UP
System.out.println("Price: " + bd.setScale(2, RoundingMode.UP)); 
// Price: 19.55

// RoundingMode.DOWN
System.out.println("Price: " + bd.setScale(2, RoundingMode.DOWN)); 
// Price: 19.54
```

## `String.format()` method

The `String.format()` method is typically to [format a string in Java](https://attacomsian.com/blog/java-string-format). It can also be used for rounding a double number to 2 decimal places. The only drawback is there is no way to set the rounding mode.

```java
double price = 19.5475;

System.out.println("Price: " + String.format("%.2f", price));
// Price: 19.55
```

## `Math.round()` method

The `Math.round()` method is another way to round a double or floating point number to 2 decimal places:

```java
double price = 19.5475;

double rounded = Math.round(price * 100D) / 100D;
System.out.println("Price: " + rounded);
// Price: 19.55
```
