四舍五入在Android中无法正常工作

时间:2015-09-15 14:45:33

标签: java android

我使用以下代码来舍入十进制数

private float roundOffTwoDigits(float number) {
    DecimalFormat toTheFormat = new DecimalFormat("0.0");
    toTheFormat.setRoundingMode(RoundingMode.DOWN);
    number = Float.valueOf(toTheFormat.format(number));
    return number;
}

现在有我得到的输出

输入输出

2.2> 2.2

2.21> 2.2

2.28> 2.2

2.4> 2.4

2.6> 2.5(为什么2.5应该是2.6)

2.8> 2.7(为什么2.7应该是2.8)

因此,即使是小数位后面的数字,如果大于5,也会减少不应发生的值。

有人在这里用Is floating point math broken?这个问题标记了我的问题,我不确定为什么?

这个问题与java和android完全无关,也没有我期待的答案和讨论。

3 个答案:

答案 0 :(得分:5)

该方法已正确舍入。 2.6无法完全代表float。当您撰写float a = 2.6F;时,a确实是

2.599999904632568359375

要正确执行此操作,您应该完全免除float,并使用BigDecimal及其String构造函数执行此操作。

答案 1 :(得分:0)

听起来您想要添加Math.floor()。这将使您的代码始终舍入到最高值。

答案 2 :(得分:0)

你可以使用一种解决方法,因为Paul完全解释了所有的动机,你可以添加一个控件:

private float roundOffTwoDigits(float number) {
    DecimalFormat toTheFormat = new DecimalFormat("0.0");
    toTheFormat.setRoundingMode(RoundingMode.DOWN);
    float roundedNumber = Float.valueOf(toTheFormat.format(number));
    //add a control to check if the code was wrongly rounded
    if((number - roundedNumber) >= 0,1){
        roundedNumber += 0,1
    }
    return roundedNumber;
}

这样,如果数字四舍五入到很多,你就会得到正确的结果。 我知道,它只是一种解决方法,但应该可行

编辑我写了一个小数,修复了