BigDecimal precise calculation and traps
BigDecimal is usually used when accurate computation is involved. The following is a summary of the incorrect use of BigDecimal.
Conclusion: Initialize the BigDecimal variable:
// BigDecimal initialize public static void testBigDecimalinit () {BigDecimal num1 = new BigDecimal (0.1); System. out. println ("Pit Point 1: num1 =" + num1); // pit Point 1: num1 = 0.1000000000000000055511151231257827021181583404541015625 BigDecimal num2 = new BigDecimal ("0.1"); System. out. println ("Correct syntax: num2 =" + num2); // correct syntax: num2 = 0.1}
Conclusion: Try to use
StringIn the form of initialization, because decimals cannot be accurately expressed within the computer. Compare the BigDecimal type variables with the values of 0. Use compareTo instead of equals:
if (num1.compareTo(BigDecimal.ZERO)>0) if (num1.compareTo(BigDecimal.ZERO)<0) if (num1.compareTo(BigDecimal.ZERO)==0)
// Compare the public static void testBigDecimalCompareTo () {BigDecimal num1 = new BigDecimal ("0.1"); BigDecimal num2 = new BigDecimal ("0.100"); if (! Num1.equals (num2) {System. out. println ("Point 1, compare the size with equals, num1 =" + num1 + ", num2 =" + num2 + "[not equal]");} if (! (Num1 = num2) {System. out. println ("Pit point 2, Use = Operator to compare the size, num1 =" + num1 + ", num2 =" + num2 + "[not equal ]");} if (num1.compareTo (num2) = 0) {System. out. println ("correct size comparison, use compareTo, num1 =" + num1 + ", num2 =" + num2 + "[equal ]");}}
Conclusion: whether the Compare size or value is equal, use
CompareToWhen division of the BigDecimal method is different, problems may occur, such as 1/3:
// BigDecimal division public static void testBigDecimalDivide () {BigDecimal num1 = new BigDecimal ("1"); // pitfall: Exception in thread "main" java. lang. arithmeticException: Non-terminating decima l expansion; no exact representable decimal result. // System. out. println ("point writing 1:" + num1.divide (new BigDecimal ("3"); // System. out. println ("point writing 2:" + num1.divide (new BigDecimal ("3 ")). setScale (2, BigDecimal. ROUND_DOWN); System. out. println ("Correct syntax:" + num1.divide (new BigDecimal ("3"), 2, BigDecimal. ROUND_HALF_DOWN ));}
Conclusion: It is set only when divide is used.Number of decimal places and rounding mode to be preciseIn order to avoid problems that cannot be accurately expressed.