Preface
As we all know, Java provides the API class BigDecimal in the java.math package, which is used to perform precise operations on numbers with more than 16 significant bits. Double precision floating point variable double can handle 16-bit significant numbers. In practical applications, larger or smaller numbers need to be computed and processed. float and double can only be used for scientific calculations or engineering calculations. java.math.BigDecimal should be used in commercial calculations.
What BigDecimal creates is an object. We cannot directly perform mathematical operations on its objects using traditional arithmetic operators such as +, -, *, and /, but must call its corresponding method.
The parameters in the method must also be BigDecimal objects. A constructor is a special method of a class, specifically used to create objects, especially objects with parameters.
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("==================="); // 不同类型转为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("==================="); // 加BigDecimal add = ma.add(mb); System.out.println("加法:"+add); // Subtraction BigDecimal sub = ma.subtract(mb); System.out.println("Subtraction: "+sub); // Multiply BigDecimal mul = mb.multiply(md); System.out.println("Multiply: "+mul); // Divide BigDecimal div = mb.divide(md); System.out.println("Divide: "+div); System.out.println("================================================================================================================================================================================================================================================================================================================================================================================================== System.out.println("Round: "+mc); System.out.println("====================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================Summarize
The above is the entire content of this article. I hope the content of this article will be of some help to your study or work. If you have any questions, you can leave a message to communicate.