Use this article to record your learning process
Article Directory
Remarks
For numbers that do not require any accurate calculation precision, you can directly use float and double, but if you need the result of precision calculation, you must use the BigDecimal class, and the BigDecimal class can also be used for large numbers.
BigDecimal addition, subtraction, multiplication and division
BigDecimal num1 = new BigDecimal("10");
BigDecimal num2 = new BigDecimal("5");
BigDecimal result = null;
// 加法 输出结果 10 + 5 = 15
result = num1.add(num2);
System.out.println(result);
// 减法 输出结果 10 - 5 = 5
result = num1.substract(num2);
System.out.println(result);
// 乘法 输出结果 10 * 5 = 50
result = num1.multiply(num2);
System.out.println(result);
// 除法 输出结果 10 / 5 = 2
result = num1.divide(num2);
System.out.println(result);
BigDecimal compare size
BigDecimal num1 = new BigDecimal("0");
BigDecimal num2 = new BigDecimal("1");
BigDecimal num3 = new BigDecimal("2");
// comNum 是用来比较的值
BigDecimal comNum = new BigDecimal("0");
System.out.println(num1.compareTo(comNum)); //小于时,返回 -1
System.out.println(num2.compareTo(comNum)); //等于时,返回 0
System.out.println(num3.compareTo(comNum)); //大于时,返回 1
Precautions for using BigDecimal
- BigDecimal is immutable, just like String, all its operations will generate a new object, so
amount.add(thisAmout);
Is wrong, the correct one should be as follows:
amount = amount.add(thisAmout);
- Do not use the equals method to compare BigDecimal objects, because its equals method will compare the scale, if the scale is not the same, it will return false
BigDecimal a = new BigDecimal("2.00");
BigDecimal b = new BigDecimal("2.0");
System.out.println(a.equals(b)); // false
So you should use compareTo() and signum() methods to compare