Home »
Java »
Java Reference »
Java BigDecimal Class
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".
Syntax:
public BigDecimal round(MathContext ma_co);
Parameter(s):
- 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.
Example:
// 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);
}
}
Output
b_dec1.round(ma_co): 1321
b_dec2.round(ma_co): 100.3