The basic usage of BigDecimal for addition subtraction multiplication and division in java

  • 2020-05-19 04:59:21
  • OfStack


It is well known that Java provides the API class BigDecimal in the java.math package for performing precise operations on Numbers over 16 significant bits. The double-precision floating point variable double can handle 16-bit significant Numbers. In practical applications, larger or smaller Numbers need to be calculated and processed. float and double can only be used for scientific or engineering calculations. They are used in business calculations java.math.BigDecimal .

What BigDecimal creates is an object, and we cannot use the traditional arithmetic operators +, -, *, / to directly perform mathematical operations on its object, but we must call its corresponding methods.

The parameter in the method must also be an BigDecimal object. Constructors are special methods of a class that are used to create objects, especially objects with arguments.

The sample code is as follows

import java.math.BigDecimal;
public class T {
 public static void main(String[] args) {
 String a = "9999.9999";
 int b = 9999;
 double c = 9999.9999;
 char d = 99;
 //  Different types to BigDecimal
 BigDecimal ma = new BigDecimal(a);
 BigDecimal mb = new BigDecimal(b);
 BigDecimal mc = new BigDecimal(c);
 BigDecimal md = new BigDecimal(d);
 //  add 
 BigDecimal add = ma.add(mb);
 System.out.println(" Add: "+add);
 //  Reduction of 
 BigDecimal sub = ma.subtract(mb);
 System.out.println(" Subtraction: "+sub);
 //  take 
 BigDecimal mul = mb.multiply(md);
 System.out.println(" Method: "+mul);
 //  In addition to 
 BigDecimal div = mb.divide(md);
 System.out.println(" Division: "+div);
 mc = mc.setScale(2, BigDecimal.ROUND_HALF_UP);
 System.out.println("4 Give up 5 In: "+mc);
 mc = mc.negate();
 System.out.println(" Negative: "+mc);


The above is the whole content of this article, I hope the content of this article to your study or work can bring 1 definite help, if you have questions you can leave a message to communicate.

Related articles: