我目前正在研究如何使用Math.round方法将8.3到8.5或8.6到9.0的数量取整。
我当前的处理方式是检查初始值是否小于四舍五入后的值,然后检查+.5或-.5。
像这样:
if(amountB < Math.round(amountB))
{
System.out.println(Math.round(amountB ) - .5);
}
但是那并不是我想要的那样,即使输入为8.6,它总是输出8.5。
谢谢您的建议。
答案 0 :(得分:1)
我会这样:
public class MyClass {
private static double myRound(double x) {
return Math.ceil(x*2.0) /2.0;
}
public static void main(String args[]) {
double x = 8.2;
double y = 8.6;
double z = 8.8;
System.out.println("" + x + " rounded upwards is = " + myRound(x));
System.out.println("" + y + " rounded upwards is = " + myRound(y));
System.out.println("" + z + " rounded upwards is = " + myRound(z));
}
//8.2 rounded is = 8.5
//8.6 rounded is = 9.0
//8.8 rounded is = 9.0
}
答案 1 :(得分:0)
您可以尝试这个;
double rounded = Math.round(x * 2.0) / 2.0;
2.0来自1 / 0.5