Java – How to round a BigDecimal value in Java ?

Problem Statement

You need round the BigDecimal value in your Java program.

Solution

Use the setScale method that is defined in the BigDecimal to round the value of the BigDecimal. You can also set the parameters like BigDecimal.ROUND_HALF_UP etc to the method.

import java.math.BigDecimal;

public class Main {

    public static void main(String[] args) {

        System.out.println("Abundantcode.com Java Tutorials");

        BigDecimal input1 = new BigDecimal(10102.15679);
        BigDecimal output = input1.setScale(2,BigDecimal.ROUND_HALF_UP);
        System.out.println(output);

    }
}


Output of the above program is

Abundantcode.com Java Tutorials

10102.16

%d