实现说明
真正干活的是类 MathContextDemo和函数 main,其余都是接线。
使用要点
- 跑完文件,输出里会留下标记——
interest(16 digits):、amount / 3:、HALF_EVEN:。
常见问题
运行「MathContext 精度与舍入」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 interest(16 digits):、amount / 3:、HALF_EVEN: 标签标明各步骤。
核心语句
BigDecimal interest = amount.multiply(rate, MathContext.DECIMAL64);
MathContext money = new MathContext(6, RoundingMode.HALF_UP);
BigDecimal amount = new BigDecimal("1234.5678");
代码示例
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
public class MathContextDemo {
public static void main(String[] args) {
BigDecimal amount = new BigDecimal("1234.5678");
BigDecimal rate = new BigDecimal("0.0725");
// DECIMAL64:16 位有效数字
BigDecimal interest = amount.multiply(rate, MathContext.DECIMAL64);
System.out.println("interest(16 digits): " + interest);
// 自定义精度 6 位 + HALF_UP:金额常用口径
MathContext money = new MathContext(6, RoundingMode.HALF_UP);
System.out.println("amount / 3: " + amount.divide(new BigDecimal("3"), money));
// 同一除法在不同舍入模式下的差异
BigDecimal one = BigDecimal.ONE;
BigDecimal three = new BigDecimal("3");
System.out.println("HALF_EVEN: " + one.divide(three, new MathContext(6, RoundingMode.HALF_EVEN)));
System.out.println("HALF_UP: " + one.divide(three, new MathContext(6, RoundingMode.HALF_UP)));
System.out.println("DOWN: " + one.divide(three, new MathContext(6, RoundingMode.DOWN)));
// 不带 MathContext 且除不尽时抛 ArithmeticException
try {
one.divide(three);
} catch (ArithmeticException e) {
System.out.println("no context: " + e.getClass().getSimpleName());
}
System.out.println("rounded: " + new BigDecimal("1.234567890123456789").round(MathContext.DECIMAL64));
}
}