来自 BigDecimal 和 MathContext 的行为不一致



我看到 BigDecimal 的一些奇怪行为当我使用 mathContext 进行除法时,输出与通过直接提供比例和舍入模式进行除法时不同这是一个我认为应该提供相同输出的示例

public static void main(String...args){
    MathContext mc = new MathContext(3,RoundingMode.HALF_UP);
    BigDecimal four = new BigDecimal(4);
    BigDecimal three = new BigDecimal(3);
    System.out.println(four.divide(three,3,RoundingMode.HALF_UP));
    System.out.println(four.divide(three,mc));
}

输出:

1.333
1.33

在使用MathContext时,量表的处理方式似乎有所不同。或者我不明白什么时候使用哪个。

BigDecimaldivide方法允许您指定结果的比例,松散地说是小数位数。 scale = 3表示数字将以 3 位小数表示。 负刻度表示整数末尾的无意义零的数量 - 因此,例如,要四舍五入到最接近的 1000,您可以指定 scale = -3

four.divide(three,3,RoundingMode.HALF_UP);  // scale = 3, so round to 3 decimal places

MathContext是不同的。 它允许您指定精度 - 即有效位数。 这与规模不同。

MathContext mc = new MathContext(3,RoundingMode.HALF_UP);
four.divide(three, mc); // precision = 3, so round to 3 significant figures

最新更新