为什么 BigDecimal return 这个值四舍五入后?
Why does BigDecimal return this value after rounding half up?
为什么 BigDecimal
return 这个值四舍五入后不是预期值,我怎样才能达到这个值?
// EXPECTED 0.45
// RETURNS 0.45
System.out.println(BigDecimal.valueOf(Double.parseDouble("0.45"))
.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
// EXPECTED 0.45
// RETURNS 0.45
System.out.println(BigDecimal.valueOf(Double.parseDouble("0.445"))
.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
// EXPECTED 0.45
// RETURNS 0.44
System.out.println(BigDecimal.valueOf(Double.parseDouble("0.4445"))
.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
这是对字面问题的回答
Why does BigDecimal return this value after rounding half up instead
of the expected value and how can i reach this?
应用于 0.4445 四舍五入为 0.44 而不是 "expected" 0.45。
Rounding mode to round towards "nearest neighbor" unless both
neighbors are equidistant, in which case round up.
两个邻居的比例因子是0.44和0.45。 0.4445 和 0.44 之间的绝对差为 0.0045。 0.4445 和 0.45 之间的绝对差为 0.0055。邻居不等距,0.44 是最近的邻居。
如果您真的非常想要一种奇怪且不必要地不准确的舍入模式,请使用 BigDecimal 的 toString 方法来获取完整的字符串表示形式。然后您可以使用字符串操作以任何您喜欢的方式对其进行处理。
为什么 BigDecimal
return 这个值四舍五入后不是预期值,我怎样才能达到这个值?
// EXPECTED 0.45
// RETURNS 0.45
System.out.println(BigDecimal.valueOf(Double.parseDouble("0.45"))
.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
// EXPECTED 0.45
// RETURNS 0.45
System.out.println(BigDecimal.valueOf(Double.parseDouble("0.445"))
.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
// EXPECTED 0.45
// RETURNS 0.44
System.out.println(BigDecimal.valueOf(Double.parseDouble("0.4445"))
.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
这是对字面问题的回答
Why does BigDecimal return this value after rounding half up instead of the expected value and how can i reach this?
应用于 0.4445 四舍五入为 0.44 而不是 "expected" 0.45。
Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.
两个邻居的比例因子是0.44和0.45。 0.4445 和 0.44 之间的绝对差为 0.0045。 0.4445 和 0.45 之间的绝对差为 0.0055。邻居不等距,0.44 是最近的邻居。
如果您真的非常想要一种奇怪且不必要地不准确的舍入模式,请使用 BigDecimal 的 toString 方法来获取完整的字符串表示形式。然后您可以使用字符串操作以任何您喜欢的方式对其进行处理。