Java Math.floor()、Math.ceil()和Math.round()四舍五入的使用及区别

Math.floor()、Math.ceil()和Math.round()都是对浮点数取整(floor和ceil返回不带小数的double,round返回long)

  • floor字面意思为地板,返回的是小于或等于该数值的最大的整数
  • ceil字面意思是天花板,返回的是大于或等于该值的最小的整数
  • round就是我们常见的四舍五入,不再多说

直接看下demo及运行结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class Test4 {
public static void main(String[] args) {
System.out.println("Math.floor(1.0) = " + Math.floor(1.0));
System.out.println("Math.floor(1.4) = " + Math.floor(1.4));
System.out.println("Math.floor(1.5) = " + Math.floor(1.5));
System.out.println("Math.floor(1.6) = " + Math.floor(1.6));
System.out.println("Math.floor(-1.0) = " + Math.floor(-1.0));
System.out.println("Math.floor(-1.4) = " + Math.floor(-1.4));
System.out.println("Math.floor(-1.5) = " + Math.floor(-1.5));
System.out.println("Math.floor(-1.6) = " + Math.floor(-1.6));

System.out.println("Math.ceil(1.0) = " + Math.ceil(1.0));
System.out.println("Math.ceil(1.4) = " + Math.ceil(1.4));
System.out.println("Math.ceil(1.5) = " + Math.ceil(1.5));
System.out.println("Math.ceil(1.6) = " + Math.ceil(1.6));
System.out.println("Math.ceil(-1.0) = " + Math.ceil(-1.0));
System.out.println("Math.ceil(-1.4) = " + Math.ceil(-1.4));
System.out.println("Math.ceil(-1.5) = " + Math.ceil(-1.5));
System.out.println("Math.ceil(-1.6) = " + Math.ceil(-1.6));

System.out.println("Math.round(1.0) = " + Math.round(1.0));
System.out.println("Math.round(1.4) = " + Math.round(1.4));
System.out.println("Math.round(1.5) = " + Math.round(1.5));
System.out.println("Math.round(1.6) = " + Math.round(1.6));
System.out.println("Math.round(-1.0) = " + Math.round(-1.0));
System.out.println("Math.round(-1.4) = " + Math.round(-1.4));
System.out.println("Math.round(-1.5) = " + Math.round(-1.5));
System.out.println("Math.round(-1.6) = " + Math.round(-1.6));
}
}

Click and drag to move

运行结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Math.floor(1.0) = 1.0
Math.floor(1.4) = 1.0
Math.floor(1.5) = 1.0
Math.floor(1.6) = 1.0
Math.floor(-1.0) = -1.0
Math.floor(-1.4) = -2.0
Math.floor(-1.5) = -2.0
Math.floor(-1.6) = -2.0
Math.ceil(1.0) = 1.0
Math.ceil(1.4) = 2.0
Math.ceil(1.5) = 2.0
Math.ceil(1.6) = 2.0
Math.ceil(-1.0) = -1.0
Math.ceil(-1.4) = -1.0
Math.ceil(-1.5) = -1.0
Math.ceil(-1.6) = -1.0
Math.round(1.0) = 1
Math.round(1.4) = 1
Math.round(1.5) = 2
Math.round(1.6) = 2
Math.round(-1.0) = -1
Math.round(-1.4) = -1
Math.round(-1.5) = -1
Math.round(-1.6) = -2

Click and drag to move

需要注意的是正负值处理后的结果

比如

Math.floor(1.5) = 1.0,Math.floor(-1.5) = -2.0

Math.ceil(1.5) = 2.0,Math.ceil(-1.5) = -1.0

Math.round(1.5) = 2,Math.round(-1.5) = -1