Detailed explanation of BigDecimal usage



Introduction to BigDecimal

The API class BigDecimal provided by Java in the java.math package is used to perform precise operations on numbers with more than 16 significant digits. The double-precision floating-point variable double can handle a 16-bit significand.


BigDecimal usage:

What BigDecimal creates is an object, and arithmetic operations such as +, -, *, / etc. cannot be used, and its corresponding related methods must be called.

And, the parameters in the method must also be BigDecimal objects.

Constructor of BigDecimal

  1. BigDecimal(int) creates an object with the integer value specified by the argument.
  2. BigDecimal(double) Creates an object with the double value specified by the argument.
  3. BigDecimal(long) Creates an object with the long integer value specified by the argument.
  4. BigDecimal(String) Creates an object with the numeric value specified by the argument as a string.
BigDecimal b = new BigDecimal(0);
BigDecimal b = new BigDecimal(1.2);
BigDecimal b = new BigDecimal("2.3");

String constructors are completely predictable: writing newBigDecimal("0.1") will create a BigDecimal that is exactly equal to the expected 0.1. Therefore, in comparison, it is generally recommended to use the String constructor in preference.

When double must be used as the source for a BigDecimal, note that this constructor provides an exact conversion; it does not provide the same result as using the Double.toString(double) method followed by the BigDecimal(String) constructor , convert double to String. To get this result, use the static valueOf(double) method.

Description of common methods of BigDecimal

  1. add(BigDecimal) Adds the values ​​in the BigDecimal object and returns this object.
  2. subtract(BigDecimal) Subtracts the values ​​in the BigDecimal object and returns this object.
  3. multiply(BigDecimal) Multiplies the values ​​in the BigDecimal object and returns this object.
  4. divide(BigDecimal) Divide the values ​​in the BigDecimal object and return this object.
  5. toString() converts the value of a BigDecimal object to a string.
  6. doubleValue() returns the value in a BigDecimal object as a double.
  7. floatValue() returns the value in a BigDecimal object as a single-precision number.
  8. longValue() returns the value in a BigDecimal object as a long integer.
  9. intValue() returns the value in the BigDecimal object as an integer.
item.setScore(
    (value.multiply(lmd).add((statuValue.divide(targetValue,3,RoundingMode.HALF_UP))
    .multiply(lmd))).multiply(new BigDecimal(100))
);

BigDecimal formatting

Since the format() method of the NumberFormat class can use a BigDecimal object as its parameter, you can use BigDecimal to control the formatting of currency values, percent values, and general values ​​that exceed 16 significant digits.

Take the use of BigDecimal for currency and percentage formatting as an example. First, create a BigDecimal object, after performing the arithmetic operation of BigDecimal, establish references to currency and percentage formatting respectively, and finally use the BigDecimal object as the parameter of the format() method to output its formatted currency value and percentage.

public static void main(String[] args) {  
    NumberFormat currency = NumberFormat.getCurrencyInstance(); //建立货币格式化引用   
    NumberFormat percent = NumberFormat.getPercentInstance();  //建立百分比格式化引用   
    percent.setMaximumFractionDigits(3); //百分比小数点最多3位   

    BigDecimal loanAmount = new BigDecimal("15000.48"); //贷款金额  
    BigDecimal interestRate = new BigDecimal("0.008"); //利率     
    BigDecimal interest = loanAmount.multiply(interestRate); //相乘  

    System.out.println("贷款金额:\t" + currency.format(loanAmount));   
    System.out.println("利率:\t" + percent.format(interestRate));   
    System.out.println("利息:\t" + currency.format(interest));   
}  

//贷款金额: ¥15,000.48 利率: 0.8% 利息: ¥120.00

BigDecimal comparison

publicstaticvoidmain(String[]args){  
    BigDecimala=newBigDecimal("1");  
    BigDecimalb=newBigDecimal("2");  
    BigDecimalc=newBigDecimal("1");  
    intresult1=a.compareTo(b);  
    intresult2=a.compareTo(c);  
    intresult3=b.compareTo(a);  
    System.out.println(result1);  
    System.out.println(result2);  
    System.out.println(result3);  
} 

// -1   0  1

That is, if the number on the left is larger than the number on the right, it returns 1, if it is equal, it returns 0, and if it is smaller than the number on the right, it returns -1. Note that you cannot use equals for equality, the equals comparison is the address of two BigDecimal objects.


BigDecimalSummary

Use BigDecimal when you need precise decimal calculations. BigDecimal's performance is worse than double and float, especially when dealing with large and complex operations. Therefore, it is not necessary to use BigDecimal for general precision calculations.

Try to use a constructor with a parameter type of String.

BigDecimal is immutable (immutable), a new object will be generated each time the four operations are performed, so remember to save the value after the operation when doing addition, subtraction, multiplication and division.

When using BigDecimal for division (.divide), if the result is an inexhaustible number, an exception will be thrown:

java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.

So, it is necessary to use the constructed model to format the decimal point:


b.divide(new BigDecimal(3),2,BigDecimal.ROUND_HALF_UP);   
BigDecimal.setScale();//用于格式化小数点     
setScale(1);//表示保留以为小数,默认用四舍五入方式     
setScale(1,BigDecimal.ROUND_DOWN);//直接删除多余的小数位,如2.35会变成2.3     
setScale(1,BigDecimal.ROUND_UP);//进位处理,2.35变成2.4     
setScale(1,BigDecimal.ROUND_HALF_UP);//四舍五入,2.35变成2.4    
setScaler(1,BigDecimal.ROUND_HALF_DOWN);//四舍五入,2.35变成2.3,如果是5则向下舍 

1. ROUND_UP
2. A rounding mode that rounds away from zero.
3. Always increment the number before discarding the non-zero part (always add 1 to the number preceding the non-zero discard part).
4. Note that this rounding mode never reduces the size of the computed value.
5.2, ROUND_DOWN
6. Rounding mode close to zero.
7. Never increment a number before discarding a part (never add 1 to the number preceding the discarded part, i.e. truncate).
8. Note that this rounding mode never increases the size of the calculated value.
9.3, ROUND_CEILING
10. Rounding mode close to positive infinity.
11. If BigDecimal is positive, the rounding behavior is the same as ROUND_UP;
12. If it is negative, the rounding behavior is the same as ROUND_DOWN.
13. Note that this rounding mode never reduces the calculated value.
14.4, ROUND_FLOOR
15. Rounding mode close to negative infinity.
16. If BigDecimal is positive, the rounding behavior is the same as ROUND_DOWN;
17. If it is negative, the rounding behavior is the same as ROUND_UP.
18. Note that this rounding mode never adds to the calculated value.
19.5, ROUND_HALF_UP
20. Round to the "nearest" number, if the distance from two adjacent numbers is equal, the rounding mode of rounding up.
21. If the discarded part is >= 0.5, the rounding behavior is the same as ROUND_UP; otherwise, the rounding behavior is the same as ROUND_DOWN.
22. Note that this is the rounding mode (rounding) that most of us were taught in elementary school.
23.6, ROUND_HALF_DOWN
24. Round to the "closest" number, if the distance from two adjacent numbers is equal, it is the rounding mode of rounding up.
25. If the rounding part is > 0.5, the rounding behavior is the same as ROUND_UP; otherwise, the rounding behavior is the same as ROUND_DOWN (rounding down).
26.7, ROUND_HALF_EVEN
27. Round to the "closest" number, if the distance from two adjacent numbers is equal, then round to the adjacent even number.
28. If the number to the left of the discarded part is odd, the rounding behavior is the same as ROUND_HALF_UP;
29. ​​If it is even, the rounding behavior is the same as ROUND_HALF_DOWN.
30. Note that this rounding mode minimizes accumulation errors when repeating a series of calculations.
31. This rounding mode is also known as "Banker's Rounding" and is mainly used in the United States. Rounding up, five out of two cases.
32. If the previous digit is an odd number, it is put in place, otherwise it is discarded.
33. The following example retains 1 decimal point, then the result of this rounding method.
34.1.15>1.2 1.25>1.2
35.8, ROUND_UNNECESSARY
36. Assert that the requested operation has an exact result, so no rounding is required.
37. Throws an ArithmeticException if this rounding mode is specified for an operation that obtains an exact result.







Related content source:
Detailed explanation of BigDecimal usage

The division of BigDecimal is not complete and an error is reported

BigDecimal division accurate calculation and pits

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324482655&siteId=291194637