BigDecimal type operations in Java
Double-precision floating-point variable double can handle a 16-bit valid number. In practical applications, larger or smaller numbers need to be calculated and processed. Java provides the API class BigDecimal in the Java.math package to perform precise operations on the number of more than 16 significant bits. The main constructors and methods of the BigDecimal class are listed in table 5.7.
Constructor description
BigDecimal (int) Creates an object with the integer value specified by the parameter.
BigDecimal (double) creates an object with the double value specified by the parameter.
BigDecimal (long) creates an object with a long integer value specified by the parameter.
BigDecimal (String) creates an object that has the numeric value specified by the parameter as a string.
Method description
Add (BigDecimal) BigDecimal the value in the object, and then returns the object.
Subtract (BigDecimal) subtracts the value from the BigDecimal object and returns the object.
Multiply (BigDecimal) multiplies the values in the BigDecimal object and returns the object.
Divide (BigDecimal) divides the values in the BigDecimal object, and then returns the object.
ToString () Converts the numeric value of the BigDecimal object to a string.
Doublevalue () returns the value in the BigDecimal object as a double-precision number.
Floatvalue () returns the value in the BigDecimal object as a single-precision number.
Longvalue () returns the value in the BigDecimal object as a long integer.
Intvalue () returns the value in the BigDecimal object as an integer.
Note that because a general numeric type, such as double, does not accurately represent numbers above 16-bit valid numbers, it makes sense to apply the BigDecimal (String) constructor to create objects when using BigDecimal. In addition, BigDecimal creates objects, and we cannot use traditional + 、-、 *,/et arithmetic operators to perform mathematical operations on their objects directly, but must call their corresponding methods. The arguments in the method must also be BigDecimal objects.
eg
Multiply data by two bigdecimal types:
BigDecimal a = new BigDecimal (15124);
BigDecimal B = new BigDecimal (15124);
BigDecimal C = a.multiply (b);
BigDecimal type operations in Java