Java BigDecimal divide examples

In this example, Java bigdecimal
class divide(BigDecimal divisor, int scale, int roundingMode) method working
is demonstrated. Example contains scale feature which is an integer type value that defines number of digits after decimal. Here the scale of the quotient will be specified in the program.
Also in the example, bigdecimal class ROUND_FLOOR
field is used that defines the Rounding mode to round towards negative infinity. Method throws Arithmetic Exception in following cases when the specified Rounding mode is
ROUND_UNNECESSARY,
when the divisor value is zero and when the specified rounding mode does not represent a valid rounding mode.
With divisor value zero, the rounding mode becomes equal to ROUND_UNNECESSARY therefore method throws Arithmetic Exception ,
when the divisor value is zero.
Method also throws IllegalArgumentException in the
case when the specified rounding mode is not a valid rounding mode.
Syntax for using the method:
public BigDecimal divide(BigDecimal divisor, int scale, int
roundingMode)
bigdecimal_objectName =
bigdecimal_objectDividendName.bigdecimal.divide(bigdecimal_objectDivisorName, int scale, int
roundingMode);
Java_BigDecimal_divide_int_scale_int_roundingMode.java
import java.math.BigDecimal;
import java.text.NumberFormat;
public class Java_BigDecimal_divide_int_scale_int_roundingMode {
public static void main(String args[]) {
System.out.println("Actual PI value with no " +
"scale defined : " + (double) 22 / 7);
int i = 22, j = 7;
BigDecimal a = new BigDecimal(i);
BigDecimal b = new BigDecimal(j),
c = new BigDecimal(0);
c = a.divide(b, 5, BigDecimal.ROUND_FLOOR);
System.out.println("PI value with scale 5 : "
+ c);
BigDecimal m = new BigDecimal(i);
BigDecimal n = new BigDecimal(j),
o = new BigDecimal(0);
// Creating NumberFormat class num object
NumberFormat num = NumberFormat.getInstance();
// Invoking .setMinimumFraction() in object num
num.setMinimumFractionDigits(5);
System.out.println("Formated PI value : "
+ num.format(c));
/*
* Here an Arithmetic Exception is thrown by method
*
* i = 22; j = 0;
* BigDecimal x = new BigDecimal(i);
* BigDecimal y = new BigDecimal(j),
* z = new BigDecimal(0);
*
* z = x.divide(y, 4, BigDecimal.ROUND_FLOOR);
* System.out.println("PI value with scale 4 : "
* + c);
*/
}
}
|
Download the source code

|