我想我找到了一个窃听器:
MathContext mathContext = new MathContext(5, RoundingMode.HALF_UP);
result = BigDecimal.valueOf(0.004798).round(mathContext); // fails
// result is 0.004798!!! (same value)我不得不使用以下备选方案:
BigDecimal bigDecimal = BigDecimal.valueOf(0.004798);
BigDecimal new_divisor = BigDecimal.valueOf(1, 5);
bigDecimal_array = bigDecimal.divideAndRemainder(new_divisor);
MathContext mathContext = new MathContext(5, RoundingMode.HALF_UP);
result = bigDecimal.subtract(bigDecimal_array[1], mathContext);
result = result.stripTrailingZeros();在我看来,这个错误(如果是的话)是非常危险的。
发布于 2022-09-10 11:19:10
不,没有窃听器。你只是误解了“精确”的意思。
要返回的数字总数由MathContext的精度设置指定;这决定了结果的精度。数字计数从精确结果的最左边的非零数字开始。
(强调我的)。
在这种情况下你有4位数。因此,任何大于或等于4的精度都不会对四舍五入产生影响。
相比较
result = BigDecimal.valueOf(0.004798).round(new MathContext(3, RoundingMode.HALF_UP));
result ==> 0.00480或使用
jshell> result = BigDecimal.valueOf(1.004798).round(new MathContext(5, RoundingMode.UP));
result ==> 1.0048表现得和你期望的一样。
https://stackoverflow.com/questions/73671276
复制相似问题