This question already has an answer here:
Java BigDecimal setScale and rounding with half_even
                                
                                    (1个答案)
                                
                        
                                2年前关闭。
            
                    
我正在尝试调试Java的HALF_EVEN取整问题,
如下所示,意外的结果是377.35,我们可以预期它会显示377.34?

有人可以帮助解释这种行为吗?

public static void main(String[] args) {


    System.out.println((new BigDecimal(0.3450)).setScale(2, RoundingMode.HALF_EVEN).toPlainString());
    //prints 0.34

    System.out.println((new BigDecimal(77.3450)).setScale(2, RoundingMode.HALF_EVEN).toPlainString());
    //prints 77.34

    System.out.println((new BigDecimal(377.3450)).setScale(2, RoundingMode.HALF_EVEN).toPlainString());
    **//prints 377.35 ?????**

    //anything larger than 256 is printing .35
    System.out.println((new BigDecimal(255.3450)).setScale(2, RoundingMode.HALF_EVEN).toPlainString());
    //prints 255.34

    System.out.println((new BigDecimal(256.3450)).setScale(2, RoundingMode.HALF_EVEN).toPlainString());
    **//prints 256.35 ?????**


}

最佳答案

new BigDecimal(377.3450)


仅此行会失去BigDecimal的所有优势,因为您首先传递的是double,并且执行了所有不需要的取整。

改写

new BigDecimal("377.3450")


...并且通常在各处使用String构造函数。在您得到“正确”答案的情况下,浮点舍入很幸运,而且方向正确。

09-30 15:17