Java RoundingMode半向上不';I don’我没料到
所以我有这个密码Java RoundingMode半向上不';I don’我没料到,java,double,rounding,Java,Double,Rounding,所以我有这个密码 public String getRounded(double amount) { DecimalFormat df = new DecimalFormat("0.00"); df.setRoundingMode(RoundingMode.HALF_UP); System.out.println(df.format(amount)); System.out.println(amount); return df.format(amount)
public String getRounded(double amount) {
DecimalFormat df = new DecimalFormat("0.00");
df.setRoundingMode(RoundingMode.HALF_UP);
System.out.println(df.format(amount));
System.out.println(amount);
return df.format(amount);
}
我添加了这两行以查看差异,这是它们显示内容的示例
输出如下所示,例如:
1.25
1.255
为什么会发生这种情况?把一半加起来不是为了取整吗?我试过用天花板,但它确实能凑起来,尽管这不是我想要的
谢谢你
double
在骗你System.out.println
在骗你
金额
不完全是1.255。它实际上是1.25499999999999989341858963598497211933135986328125
,小于确切的实数1.255
将其四舍五入,加上一半,正确返回1.25
如果你关心这样的细微差别,你需要从一开始就使用BigDecimal。
double
在骗你System.out.println
在骗你
金额
不完全是1.255。它实际上是1.25499999999999989341858963598497211933135986328125
,小于确切的实数1.255
将其四舍五入,加上一半,正确返回1.25
如果您关心这样的细微差别,您需要从一开始就使用BigDecimal。值得注意的是,
System.out.println(新的BigDecimal(amount))
会说出真相。这很有意义。感谢您值得注意的是,System.out.println(新的BigDecimal(amount))
将说出真相。这是有道理的。非常感谢。