我使用以下代码来舍入十进制数
private float roundOffTwoDigits(float number) {
DecimalFormat toTheFormat = new DecimalFormat("0.0");
toTheFormat.setRoundingMode(RoundingMode.DOWN);
number = Float.valueOf(toTheFormat.format(number));
return number;
}
现在有我得到的输出
因此,即使是小数位后面的数字,如果大于5,也会减少不应发生的值。
有人在这里用Is floating point math broken?这个问题标记了我的问题,我不确定为什么?
这个问题与java和android完全无关,也没有我期待的答案和讨论。
答案 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;
}
这样,如果数字四舍五入到很多,你就会得到正确的结果。 我知道,它只是一种解决方法,但应该可行
编辑我写了一个小数,修复了