Java RoundingMode HALF_UP 没有按预期四舍五入 [英] Java RoundingMode HALF_UP doesn't round up as expected

查看:84
本文介绍了Java RoundingMode HALF_UP 没有按预期四舍五入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个代码

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);
}

我添加了这两行以查看不同之处,这是它们显示的示例.

I've added those two lines to see the difference and this is an example of what they display.

输出是这样的:

1.25

1.255

为什么会这样?HALF_UP 的重点不是四舍五入吗?我尝试过使用 CEILING 并且它确实向上取整,尽管在这种情况下这不是我想要的.

Why does this happen? Isn't the point of HALF_UP to round up? I've tried with CEILING and it does round up, although that's not what I want in this case.

谢谢

推荐答案

double 在骗你.System.out.println 在骗你.

amount 不完全是 1.255.它实际上是1.2549999999999989341858963598497211933135986328125,小于确切的实数1.255.

amount is not exactly 1.255. It is actually 1.25499999999999989341858963598497211933135986328125, which is less than the exact real number 1.255.

使用 HALF_UP 对其进行四舍五入会正确返回 1.25.

Rounding that with HALF_UP returns, correctly, 1.25.

如果您关心这样的细微差别,则需要从一开始就使用 BigDecimal.

If you care about fine distinctions like this, you will need to use BigDecimal from the beginning.

这篇关于Java RoundingMode HALF_UP 没有按预期四舍五入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆