Working with BigDecimal values in Java

Java 8Object Oriented ProgrammingProgramming

The java.math.BigDecimal class provides operations for arithmetic, scale manipulation, rounding, comparison, hashing, and format conversion.

Two types of operations are provided for manipulating the scale of a BigDecimal −

  • scaling/rounding operations
  • decimal point motion operations

The following are some of the constructors of the BigDecimal values −

Sr.No.Constructor & Description
1BigDecimal(BigInteger val)
This constructor is used to translates a BigInteger into a BigDecimal.
2BigDecimal(BigInteger unscaledVal, int scale)
This constructor is used to translate a BigInteger unscaled value and an int scale into a BigDecimal.
3BigDecimal(BigInteger unscaledVal, int scale, MathContext mc)
This constructor is used to translate a BigInteger unscaled value and an int scale into a BigDecimal, with rounding according to the context settings.
4BigDecimal(BigInteger val, MathContext mc)
This constructor is used to translate a BigInteger into a BigDecimal rounding according to the context settings.
5BigDecimal(char[ ] in)
This constructor is used to translate a character array representation of a BigDecimal into a BigDecimal, accepting the same sequence of characters as the BigDecimal(String) constructor.
6BigDecimal(char[ ] in, int offset, int len)
This constructor is used to translate a character array representation of a BigDecimal into a BigDecimal, accepting the same sequence of characters as the BigDecimal(String) constructor, while allowing a sub-array to be specified.

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("37578975.8768");
      BigDecimal val2 = new BigDecimal("62567878.9768");
      BigDecimal val3 = new BigDecimal("72567874.3768");
      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 : 37578975.8768
Value 2 : 62567878.9768
Addition Operation = 100146854.8536
Multiplication Operation = 6265976294387200.48179648
Subtract Operation = 9999995.4000
Division Operation = 7.2568
raja
Published on 21-Dec-2018 05:57:40
Advertisements