# Display numbers with 2 decimal points using BigDecimal in Java

When working with financial data and other calculations that require a high degree of precision, Java's `BigDecimal`

class is often the go-to choice for developers. One common use case for `BigDecimal`

is to display numbers with a fixed number of decimal points, such as two decimal points for monetary values.

To display a number with two decimal points using `BigDecimal`

, you can use the `setScale()`

method. This method takes two arguments: the number of decimal places to round to, and the `RoundingMode`

to use.

Here's an example:

```
import java.math.BigDecimal;
import java.math.RoundingMode;
public class Example {
public static void main(String[] args) {
BigDecimal number = new BigDecimal("1234.56789");
BigDecimal rounded = number.setScale(2, RoundingMode.HALF_UP);
System.out.println(rounded);
}
}
```

In this example, we create a `BigDecimal`

object with the value "1234.56789". We then use the `setScale()`

method to round the number to two decimal places using the `RoundingMode.HALF_UP`

mode, which rounds up if the next digit is 5 or greater.

The output of this code would be:

`1234.57`

By using `BigDecimal`

and the `setScale()`

method with the appropriate `RoundingMode`

, you can ensure that your numbers are displayed with the precision and formatting that you need.

Leave a Reply

Related posts