{

How to Rounding Bigdecimal values with 2 Decimal Places in Java


This tutorial shows you how to round bigdecimal value with n decimal places in java

BigDecimal has the methods setScale and round to round the desired value.

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 a number of digits to limit the precision or decimal places of a Bigdecimal. RoundingMode: Rounding Mode to apply to input bigdecimal value. RoundingMode is an enum with the following constants

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

This method throws ArithmeticException

BigDecimal is an immutable class and setRound returns a new object

BigDecimal round method

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 BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.