写JAVA代码的时候,经常能够用到floor、ceil和round函数,现在看下都是怎么用的
public static double floor(double a)
public static double ceil(double a)
public static long round(double a)
public static int round(float a)
floor : 向下取整,返回不大于它的最大整数
ceil : 向上取整,返回不小于它的最小整数
round : 表示“四舍五入”,算法为Math.floor(x+0.5),即将原来的数字加上0.5后再向下取整,所以,Math.round(11.5)的结果为12,Math.round(-11.5)的结果为-11。
举个例子:
public class Test {
public static void main(String[] args) {
double[] nums = { 1.4, 1.5, 1.6, -1.4, -1.5, -1.6 };
for (double d : nums) {
test(d);
}
}
private static void test(double d) {
System.out.println("Math.floor(" + d + ")=" + Math.floor(d) + ";"
+ "Math.round(" + d + ")=" + Math.round(d) + ";"
+ "Math.ceil("+ d + ")=" + Math.ceil(d));
}
}
运行结果:
把它整理成表格,看着更清晰,更好的对比下