Math operation for BigDecimal in java

This example shows you some Math operation using BigDecimal object in java.

The BigDecimal object provides you various methods to do the math operation on it.

Below is the example of math operation on BigDecimal object.

package com.java.connect.math;
 
//Math operation for BigDecimal in java
import java.math.BigDecimal;
 
public class BigDecimalExample {
    public static void main(String[] args) {
        // Declare decimal objects
        BigDecimal decimal1 = new BigDecimal("20");
        BigDecimal decimal2 = new BigDecimal("10");
 
        // Addition
        decimal1 = decimal1.add(decimal2);
        System.out.println("Addition : " + decimal1);
        // Subtraction
        decimal1 = decimal1.subtract(decimal2);
        System.out.println("subtract : " + decimal1);
        // Multiplication
        decimal1 = decimal1.multiply(decimal2);
        System.out.println("Multiply : " + decimal1);
        // Divide
        decimal1 = decimal1.divide(decimal2);
        System.out.println("divide : " + decimal1);
        // Power
        decimal1 = decimal1.pow(2);
        System.out.println("power of 2 : " + decimal1);
        // Negative
        decimal1 = decimal1.negate();
        System.out.println("negate : " + decimal1);
    }
}

The output of the above example will be as:

Addition : 30
subtract : 20
Multiply : 200
divide : 20
power of 2 : 400
negate : -400