为什么我得到不同的BigDecimal舍入结果?

时间:2016-03-29 19:35:48

标签: java rounding

为什么我得到以下输出:

1.11

1.13

在代码下面运行时:

public static void main(String[] args) {

    double aDouble = 1.115;
    double bDouble = 1.125;

    System.out.println(roundTo2Decimal(aDouble));
    System.out.println(roundTo2Decimal(bDouble));
}

public static BigDecimal roundTo2Decimal(double doubleToRound){
    BigDecimal bigDecimal = new BigDecimal(doubleToRound);
    return bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
}

而非预期结果:

1.12

1.13?

3 个答案:

答案 0 :(得分:2)

当将1.115表示为double时,由于精度损失而发生这种情况:

1.115 = 1.114999999999999991118215803E0
1.125 = 1.125E0

答案 1 :(得分:1)

很确定这只是标准浮点不精确。 0.125 = 1/8,可以二进制表示。 0.115并不是因为它没有完全存储,而且显然是存储在远离你期望的东西的地方。尝试System.out.println双倍本身。

答案 2 :(得分:0)

<code>
//to achieve what u need change your method to
    public static BigDecimal roundTo2Decimal(double doubleToRound) {
        BigDecimal bigDecimal = new BigDecimal(doubleToRound);
        return bigDecimal.setScale(2, RoundingMode.CEILING);
    }

</code>
相关问题