Math operations for BigDecimal in Java

Java 8Object Oriented ProgrammingProgramming

Let us apply the following operations on BigDecimal using the in-built methods in Java −

Addition: add() method
Subtraction: subtract() method
Multiplication: multiply() method
Division: divide() method

Let us create three BigInteger objects −

BigDecimal val1 = new BigDecimal("37578975587.876876989");
BigDecimal val2 = new BigDecimal("62567875598.976876569");
BigDecimal val3 = new BigDecimal("72567875598.376876569");

Apply mathematical operations on them −

val1 = val1.add(val2);
System.out.println("Addition Operation = " + val1);
val1 = val1.multiply(val2);
System.out.println("Multiplication Operation = " + val1);
val2 = val3.subtract(val2);
System.out.println("Subtract Operation = " + val2);

The following is an example −

Example

 Live Demo

import java.math.BigDecimal;
public class Demo {
   public static void main(String[] argv) throws Exception {
      BigDecimal val1 = new BigDecimal("37578975587.876876989");
      BigDecimal val2 = new BigDecimal("62567875598.976876569");
      BigDecimal val3 = new BigDecimal("72567875598.376876569");
      System.out.println("Value 1 : "+val1);
      System.out.println("Value 2 : "+val2);
      val1 = val1.add(val2);
      System.out.println("Addition Operation = " + val1);
      val1 = val1.multiply(val2);
      System.out.println("Multiplication Operation = " + val1);
      val2 = val3.subtract(val2);
      System.out.println("Subtract Operation = " + val2);
      val2 = val3.divide(val2,BigDecimal.ROUND_UP);
      System.out.println("Division Operation = " + val2);
   }
}

Output

Value 1 : 37578975587.876876989
Value 2 : 62567875598.976876569
Addition Operation = 100146851186.853753558
Multiplication Operation = 6265975726688315418019.861150364510582502
Subtract Operation = 9999999999.400000000
Division Operation = 7.256787561
raja
Published on 21-Dec-2018 10:16:52
Advertisements