How to Rounding Bigdecimal values with 2 Decimal Places in Java

This tutorial is about how to round a BigDecimal value to n decimal places in Java. The BigDecimal class provides the setScale and round methods for achieving this.

You can also check my previous posts on the BigInteger class in Java.

BigDecimal setScale method

This method is used to return a BigDecimal object with a given scale and rounding mode.

Here is a syntax.

    public BigDecimal setScale(int newScale, RoundingMode roundingMode)

newScale is several digits to limit the precision or decimal places of a Bigdecimal. RoundingMode: Rounding Mode to apply to input big decimal value. RoundingMode is an enum with the following constants

  • UP
  • DOWN
  • CEILING
  • FLOOR
  • HALF_UP
  • HALF_DOWN
  • HALF_EVEN
  • UNNECESSARY

This method throws ArithmeticException if the rounding mode is UNNECESSARY.

BigDecimal is an immutable class and setRound always returns a new object

How to Round BigDecimal to the nearest whole or integer value

This example round the bigdecimal value to the nearest integer value.

It can be done in two ways, One way is using setScale, second-way using the round method.

For example, if the given value is 789123.123456789, the output is 789123.

setScale(0, RoundingMode.HALF_UP): returns whole value with removing precission

Here is an example code with the setScale method

import java.math.BigDecimal;
import java.math.RoundingMode;

public class BigDecimalTest {
    public static void main(String[] args) {
        BigDecimal bd = new BigDecimal(789123.123456789);
        BigDecimal output = bd.setScale(0, RoundingMode.HALF_DOWN);
        System.out.println(output); //789123
        BigDecimal output1 = bd.setScale(0, RoundingMode.HALF_DOWN);
        System.out.println(output1); //789123

    }
}

Here is an example code with a round method

public class BigDecimalTest {
    public static void main(String[] args) {
        BigDecimal bd = new BigDecimal(789123.123456789);
        BigDecimal output = bd.round(new MathContext(6, RoundingMode.HALF_UP));

        System.out.println(output); //789123
        BigDecimal output1= bd.round(new MathContext(6, RoundingMode.HALF_UP));
        System.out.println(output1); //789123
    }
}

The setScale method Provides an option to specify the rounding mode, whereas the round method uses MathContext for customized rounding.