The basic usage of BigDecimal for addition subtraction multiplication and division in java
- 2020-05-19 04:59:21
- OfStack
preface
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;
System.out.println("===================");
// Different types to BigDecimal
BigDecimal ma = new BigDecimal(a);
BigDecimal mb = new BigDecimal(b);
BigDecimal mc = new BigDecimal(c);
BigDecimal md = new BigDecimal(d);
System.out.println("ma:"+ma.toString());
System.out.println("mb:"+mb.toString());
System.out.println("mc:"+mc.toString());
System.out.println("md:"+md.toString());
System.out.println("===================");
// 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);
System.out.println("===================");
mc = mc.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println("4 Give up 5 In: "+mc);
System.out.println("===================");
mc = mc.negate();
System.out.println(" Negative: "+mc);
System.out.println("===================");
}
}
conclusion
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.