Java BigDecimal round() Method with Example

BigDecimal Class round() method: Here, we are going to learn about the round() method of BigDecimal Class with its syntax and example.
Submitted by Preeti Jain, on May 04, 2020

BigDecimal Class round() method

  • round() method is available in java.math package.
  • round() method is used to get a rounded BigDecimal based on the given MathContext setting when the precision value is not equal to 0 otherwise there is no effect of rounding when the precision value is equal to 0.
  • round() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • round() method may throw an exception at the time of rounding.
    ArithmeticException: This exception may throw when this BigDecimal need rounding and the mode of rounding is set to "UNNECESSARY".


    public BigDecimal round(MathContext ma_co);


  • MathContext ma_co – represents the MathContext to use in rounding BigDecimal.

Return value:

The return type of this method is BigDecimal, it returns the rounded BigDecimal based on the given MathContext.


// Java program to demonstrate the example 
// of BigDecimal round(MathContext ma_co) method of BigDecimal

import java.math.*;

public class RoundOfBD {
    public static void main(String args[]) {
        // Initialize two variables and
        // first is of "short" and second is  
        // of "String" type
        short val1 = 1321;
        String val2 = "100.24";

        // Initialize two BigDecimal objects and
        // one MathContext
        BigDecimal b_dec1 = new BigDecimal(val1);
        BigDecimal b_dec2 = new BigDecimal(val2);
        MathContext ma_co = new MathContext(4, RoundingMode.CEILING);

        // round this BigDecimal b_dec1 according to
        // the given MathContext based on precision
        // and rounding mode
        BigDecimal round = b_dec1.round(ma_co);
        System.out.println("b_dec1.round(ma_co): " + round);

        // round this BigDecimal b_dec1 according to
        // the given MathContext based on precision
        // and rounding mode
        round = b_dec2.round(ma_co);
        System.out.println("b_dec2.round(ma_co): " + round);


b_dec1.round(ma_co): 1321
b_dec2.round(ma_co): 100.3

Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.