1. When BigDecimal is added, subtracted, or multiplied, the precision will not be lost. However, when doing division, there may be situations where it cannot be divided. In this case, the precision and how to truncate must be specified.
import java.math.BigDecimal; import java.math.RoundingMode; public class Demo { public static void main(String[] args) { BigDecimal d1 = new BigDecimal("123.456"); BigDecimal d2 = new BigDecimal("23.456789"); BigDecimal d3 = d1.divide(d2, 10, RoundingMode.HALF_UP); // 保留10位小数并四舍五入 BigDecimal d4 = d1.divide(d2); // 报错:ArithmeticException,因为除不尽 } }
2. You can divide BigDecimal and find the remainder at the same time.
import java.math.BigDecimal; public class Demo { public static void main(String[] args) { BigDecimal n = new BigDecimal("22.444"); BigDecimal m = new BigDecimal("0.23"); BigDecimal[] dr = n.divideAndRemainder(m); System.out.println(dr[0]); // 97.0 System.out.println(dr[1]); // 0.134 } }
The above is the detailed content of How to use BigDecimal to perform mathematical operations in java. For more information, please follow other related articles on the PHP Chinese website!