floorReturns the largest integer not greater than the argument.

roundIt is a half-up rounding calculation, rounding up to the integer greater than it.

roundmeansrounding", the algorithm isMath.floor(x+0.5), that is, add 0.5 to the original number and then floor, soMath.round(11.5)the result is 12, and the result of Math.round(-11.5) is -11.

Let's first look at the output of the Java Math floor, ceil, rint and round methods through the following example:

Test.java

import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter a floating-point number:"); while(sc.hasNext()){ double num = sc.nextDouble(); System.out.println("Math.floor(" + num + ") = " + Math.floor(num)); System.out.println("Math.ceil(" + num + ") = " + Math.ceil(num)); System.out.println("Math.rint(" + num + ") = " + Math.rint(num)); System.out.println("Math.round(" + num + ") = " + Math.round(num)); } } }

Run the above program to test the output:

$ javac Test.java 
$ java Test
输入一个浮点数:
2.2
Math.floor(2.2) = 2.0
Math.ceil(2.2) = 3.0
Math.rint(2.2) = 2.0
Math.round(2.2) = 2
-2.2
Math.floor(-2.2) = -3.0
Math.ceil(-2.2) = -2.0
Math.rint(-2.2) = -2.0
Math.round(-2.2) = -2
-2.5
Math.floor(-2.5) = -3.0
Math.ceil(-2.5) = -2.0
Math.rint(-2.5) = -2.0
Math.round(-2.5) = -2
2.5
Math.floor(2.5) = 2.0
Math.ceil(2.5) = 3.0
Math.rint(2.5) = 2.0
Math.round(2.5) = 3
2.7
Math.floor(2.7) = 2.0
Math.ceil(2.7) = 3.0
Math.rint(2.7) = 3.0
Math.round(2.7) = 3
-2.7
Math.floor(-2.7) = -3.0
Math.ceil(-2.7) = -2.0
Math.rint(-2.7) = -3.0
Math.round(-2.7) = -3

Analyze output

1、Math.floor()Floor, i.e., the largest integer less than this number.

Math.floor(2.2) = 2.0;  
Math.floor(-2.2) = -3.0;  
Math.floor(2.5) = 2.0;  
Math.floor(-2.5) = -3.0;  
Math.floor(2.7) = 2.0;  
Math.floor(-2.7) = -3.0; 

2、Math.ceil()Ceiling, i.e., the smallest integer greater than this number.

Math.ceil(2.2) = 3.0;  
Math.ceil(-2.2) = -2.0;  
Math.ceil(2.5) = 3.0;  
Math.ceil(-2.5) = -2.0;  
Math.ceil(2.7) = 3.0;  
Math.ceil(-2.7) = -2.0;

3、Math.rint()Returns the integer closest to the value.

Note:If there are two such integers, return theeven one。

4、Math.round() rounding, but when the argument is negative it is not easy to understand. Looking directly at the source code should make it easier to understand. Note that the return type is integer.

Math.round(x) = Math.floor(x + 0.5)  

Bring the above code into the following example for testing:

Math.round(2.2) = 2;  
Math.round(-2.2) = -2;  
Math.round(2.5) = 3;  
Math.round(-2.5) = -2;  
Math.round(2.7) = 3;  
Math.round(-2.7) = -3  

Reference URL: https://blog.csdn.net/u012050154/article/details/52448260