如何将 Java 中的值四舍五入?
How to round up a value in Java?
我想对值进行四舍五入。例如,
23.0f / 10.0f = 2.3f -> round up to 3
11.0f / 10.0f = 1.1f -> round up to 2
15.0f / 10.0f = 1.5f -> round up to 2
67.0f / 10.0f = 6.7f -> round up to 7
1738.0f / 10.0 = 173.8f -> round up to 174
我目前的方法不起作用,它四舍五入到最接近的整数而不是向上:
public class Test {
private static final DecimalFormat df = new DecimalFormat("0.00");
public static void main(String[] args) {
final float a = 23;
final float b = 10;
final float k = a / b;
System.out.println(k);
final float roundup = Math.round(k * 100) / 100;
System.out.println(roundOff);
}
}
如何在 Java 中实现所需的行为?
使用Math
库,不要重新发明轮子
private int roundUp(float value){
return (int) Math.ceil(value);
}
我想对值进行四舍五入。例如,
23.0f / 10.0f = 2.3f -> round up to 3
11.0f / 10.0f = 1.1f -> round up to 2
15.0f / 10.0f = 1.5f -> round up to 2
67.0f / 10.0f = 6.7f -> round up to 7
1738.0f / 10.0 = 173.8f -> round up to 174
我目前的方法不起作用,它四舍五入到最接近的整数而不是向上:
public class Test {
private static final DecimalFormat df = new DecimalFormat("0.00");
public static void main(String[] args) {
final float a = 23;
final float b = 10;
final float k = a / b;
System.out.println(k);
final float roundup = Math.round(k * 100) / 100;
System.out.println(roundOff);
}
}
如何在 Java 中实现所需的行为?
使用Math
库,不要重新发明轮子
private int roundUp(float value){
return (int) Math.ceil(value);
}