Java.math.BigDecimal.divide() Method
Description
The java.math.BigDecimal.divide(BigDecimal divisor, int scale, int roundingMode) returns a BigDecimal whose value is (this / divisor), and whose scale is as specified. If rounding must be performed to generate a result with the specified scale, the specified rounding mode is applied.
Declaration
Following is the declaration for java.math.BigDecimal.divide() method
public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode)
Parameters
divisor - value by which this BigDecimal is to be divided
scale - scale of the BigDecimal quotient to be returned
roundingMode - rounding mode to apply
Return Value
This method returns a BigDecimal object whose value is this / divisor rounded as specified to given scale
Exception
ArithmeticException - if divisor == 0, or roundingMode == ROUND_UNNECESSARY and this.scale() is insufficient to represent the result of the division exactly
IllegalArgumentException - if roundingMode does not represent a valid rounding mode
Example
The following example shows the usage of math.BigDecimal.divide() method.
package com.tutorialspoint;
import java.math.*;
public class BigDecimalDemo {
public static void main(String[] args) {
// create 3 BigDecimal objects
BigDecimal bg1, bg2, bg3;
bg1 = new BigDecimal("16");
bg2 = new BigDecimal("3");
// divide bg1 with bg2 with 4 scale
// 1 specifies BigDecimal.ROUND_DOWN
bg3 = bg1.divide(bg2, 4, 1);
String str = "Division result is " +bg3;
// print bg3 value
System.out.println( str );
}
}
Let us compile and run the above program, this will produce the following result:
Division result is 5.3333