Java Math floor, ceil, rint, and round Usage
Category Programming Technology
floor returns the largest integer less than or equal to the given number.
round is a rounding calculation, where values are rounded up to the next integer if they are halfway or more.
round represents "round half up", with the algorithm being Math.floor(x+0.5), which means adding 0.5 to the original number and then rounding down. Therefore, Math.round(11.5) results in 12, and Math.round(-11.5) results in -11.
Let's look at the following example to see the output of the Java Math floor, ceil, rint, and round methods:
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));
}
}
}
Executing the above program produces the following output:
$ javac Test.java
$ java Test
Enter a floating-point number:
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
Analysis of Output
Math.floor() rounds down to the nearest integer, which is the largest integer less than the given 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;
Math.ceil() rounds up to the nearest integer, which is the smallest integer greater than the given 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;
Math.rint() returns the nearest integer to the given value.
Note: If there are two such integers, it returns the even one.
- Math.round() rounds half up, but it can be less intuitive when the argument is negative. The source code might be easier to understand, and it returns an integer.
Math.round(x) = Math.floor(x + 0.5)
Applying the above code to the following examples:
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: https://blog.csdn.net/u012050154/article/details/52448260