- ceil:向上取整
- floor:向下取整
- round:四舍五入
- rint:取接近它的整数 ,如果两个同样接近,往偶数靠近
ceil:向上取整
Math.ceil(11.5) = 12.0
Math.ceil(5.5) = 6.0
Math.ceil(0.7) = 1.0
Math.ceil(0.5) = 1.0
Math.ceil(0.2) = 1.0
Math.ceil(0.0) = 0.0
Math.ceil(-0.0) = -0.0
Math.ceil(-0.2) = -0.0
Math.ceil(-0.5) = -0.0
Math.ceil(-0.7) = -0.0
Math.ceil(-5.5) = -5.0
Math.ceil(-11.5) = -11.0
floor:向下取整
Math.floor(11.5) = 11.0
Math.floor(5.5) = 5.0
Math.floor(0.7) = 0.0
Math.floor(0.5) = 0.0
Math.floor(0.2) = 0.0
Math.floor(0.0) = 0.0
Math.floor(-0.0) = -0.0
Math.floor(-0.2) = -1.0
Math.floor(-0.5) = -1.0
Math.floor(-0.7) = -1.0
Math.floor(-5.5) = -6.0
Math.floor(-11.5) = -12.0
round:四舍五入
加0.5然后向下取整。
Math.round(11.5) = 12
Math.round(5.5) = 6
Math.round(0.7) = 1
Math.round(0.5) = 1
Math.round(0.2) = 0
Math.round(0.0) = 0
Math.round(-0.0) = 0
Math.round(-0.2) = 0
Math.round(-0.5) = 0
Math.round(-0.7) = -1
Math.round(-5.5) = -5
Math.round(-11.5) = -11
rint:取接近它的整数 ,如果两个同样接近,往偶数靠近
特殊情况:
1)参数本身是整数,返回参数本身。
2)如果不是数字,或者无穷大,正负0返回其本身)
Math.rint(11.5) = 12.0
Math.rint(5.5) = 6.0
Math.rint(0.7) = 1.0
Math.rint(0.5) = 0.0
Math.rint(0.2) = 0.0
Math.rint(0.0) = 0.0
Math.rint(-0.0) = -0.0
Math.rint(-0.2) = -0.0
Math.rint(-0.5) = -0.0
Math.rint(-0.7) = -1.0
Math.rint(-5.5) = -6.0
Math.rint(-11.5) = -12.0
示例:
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
double num = sc.nextDouble();
System.out.println("Math.ceil(" + num + ") = " + Math.ceil(num));
System.out.println("Math.floor(" + num + ") = " + Math.floor(num));
System.out.println("Math.round(" + num + ") = " + Math.round(num));
System.out.println("Math.rint(" + num + ") = " + Math.rint(num));
}
}
}
输出:
11.5
Math.ceil(11.5) = 12.0
Math.floor(11.5) = 11.0
Math.round(11.5) = 12
Math.rint(11.5) = 12.0
5.5
Math.ceil(5.5) = 6.0
Math.floor(5.5) = 5.0
Math.round(5.5) = 6
Math.rint(5.5) = 6.0
0.7
Math.ceil(0.7) = 1.0
Math.floor(0.7) = 0.0
Math.round(0.7) = 1
Math.rint(0.7) = 1.0
0.5
Math.ceil(0.5) = 1.0
Math.floor(0.5) = 0.0
Math.round(0.5) = 1
Math.rint(0.5) = 0.0
0.2
Math.ceil(0.2) = 1.0
Math.floor(0.2) = 0.0
Math.round(0.2) = 0
Math.rint(0.2) = 0.0
0
Math.ceil(0.0) = 0.0
Math.floor(0.0) = 0.0
Math.round(0.0) = 0
Math.rint(0.0) = 0.0
-0
Math.ceil(-0.0) = -0.0
Math.floor(-0.0) = -0.0
Math.round(-0.0) = 0
Math.rint(-0.0) = -0.0
-0.2
Math.ceil(-0.2) = -0.0
Math.floor(-0.2) = -1.0
Math.round(-0.2) = 0
Math.rint(-0.2) = -0.0
-0.5
Math.ceil(-0.5) = -0.0
Math.floor(-0.5) = -1.0
Math.round(-0.5) = 0
Math.rint(-0.5) = -0.0
-0.7
Math.ceil(-0.7) = -0.0
Math.floor(-0.7) = -1.0
Math.round(-0.7) = -1
Math.rint(-0.7) = -1.0
-5.5
Math.ceil(-5.5) = -5.0
Math.floor(-5.5) = -6.0
Math.round(-5.5) = -5
Math.rint(-5.5) = -6.0
-11.5
Math.ceil(-11.5) = -11.0
Math.floor(-11.5) = -12.0
Math.round(-11.5) = -11
Math.rint(-11.5) = -12.0