Java BigDecimal 是否需要加法舍入?

Java BigDecimal is rounding necessary with addition?

我正在使用 BigDecimal 并且我知道如果我划分我必须使用 MathContext 并告诉 ScaleRoundingMode 避免 ArithmeticException 如文档中所述:

In the case of divide, the exact quotient could have an infinitely long decimal expansion; for example, 1 divided by 3. If the quotient has a nonterminating decimal expansion and the operation is specified to return an exact result, an ArithmeticException is thrown.

在我正在处理的方法中,我必须将来自我们数据库的金额(四舍五入到小数点后两位)与来自外部服务的金额相加,我不知道这些金额的确切比例(可能是 3 位小数)。

我的问题是,我能否信任 BigDecimal 的添加方法并在不进行舍入和缩放的情况下使用它,或者始终指定所需的比例是一个好习惯?

加减法有没有特殊情况可以加ArithmeticException

如果结果的比例不适合 int.

BigDecimal.add() 将抛出 ArithmeticException

一个简单的例子是将两个具有最大和最小尺度的数字相加:

BigDecimal a = new BigDecimal(BigInteger.ONE, Integer.MIN_VALUE);
BigDecimal b = new BigDecimal(BigInteger.ONE, Integer.MAX_VALUE);
a.add(b);

如果您的应用程序需要在这样的规模下运行,那么您可能遇到一些更大的问题,而不是担心算术异常。

在不使用 MathContext 的情况下添加数字将保持适当的比例并为您提供准确的结果。根据实际值,这种方法可以使用任意数量的内存来表示越来越长的数字,而更长的数字需要更多的时间来添加。

在不使用 MathContext 的情况下添加数字并在求和后进行一次四舍五入将为您提供四舍五入到请求的 MathContext 的精确结果。内存和计算成本与第一种情况相同。

每次加法使用MathContext会产生一个与预置结果相差任意值的结果,但内存和速度会更可预测。

选择使用这些方法中的哪一种实际上取决于任务的性质,因此您需要针对每个特定情况评估和选择合适的方法。