BigDecimal 四舍五入不正确

BigDecimal Rounding incorrectly

我期待这段代码:

    double valore = 20.775;

    BigDecimal c = new BigDecimal(valore);
    c = c.setScale(2, RoundingMode.HALF_UP);


    System.out.println(c.doubleValue());

到 return 20.78,但它是 returning 20.77。

是否出错?还是我遗漏了什么?

一切正确。
您可以在 another answer on SO or read more in documentation to BigDecimal

中阅读一些高级详细信息

使用带有 double 参数的 BigDecimal 构造函数并不常见,因为它会准确地表示 double 中的内容。 所以当你写:new BigDecimal(20.775) 结果不一定是 20.775(而是你会得到类似 20.77499999999999857891452847979962825775146484375

供您测试:
1) 测试 BigDecimal 表示
a) System.out.println(new BigDecimal(20.775)); => 20.77499999999999857891452847979962825775146484375
b) System.out.println(new BigDecimal("20.775")); => 20.775

2) 使用不同的 BigDecimal 构造函数测试舍入:
a) new BigDecimal(20.775) 四舍五入后将显示 20.77.
b) new BigDecimal("20.775") 四舍五入后将显示 20.78.
c) new BigDecimal(String.valueOf(20.775) 四舍五入后将显示 20.78.

所以作为结论: 不要将 BigDecimal 构造函数与 double 参数一起使用。 而是将 BigDecimal 构造函数与 String 参数一起使用。

希望对您有所帮助