Three methods of the Java Math class ceil floor round usage

  • 2021-10-24 22:43:21
  • OfStack

ceil, floor, round Usage of Math Class

ceil () method

It means rounding up, and the result of Math. ceil (12.3) is 13, and the result of Math. ceil (-12.7) is-12;

floor () method

It means rounding down, and the result of Math. floor (12.7) is 12, and the result of Math. floor (-12.3) is-13;

round () method

It means "4 round 5 in", the result of Math. round (12.3) is 12, and the result of Math. round (-12.7) is-13;

Summary of floor, round and ceil for Math

floor returns the largest integer not greater than

round is the calculation of 4 rounded by 5 integers, and the integer is greater than it when entering

round method, which means "4 rounding 5 inputs", the algorithm is Math. floor (x+0.5), that is, adding 0.5 to the original number and rounding it down, so the result of Math. round (11.5) is 12, and the result of Math. round (-11.5) is-11.

ceil is the smallest integer not less than it

Look at examples

Math.floor Math.round Math.ceil
1.4 1 1 2
1.5 1 2 2
1.6 1 2 2
-1.4 -2 -1 -1
-1.5 -2 -1 -1
-1.6 -2 -2 -1

The test procedure is as follows:


 
public class MyTest {   
  public static void main(String[] args) {   
    double[] nums = { 1.4, 1.5, 1.6, -1.4, -1.5, -1.6 };   
    for (double num : nums) {   
      test(num);   
    }   
  }   
private static void test(double num) {   
    System.out.println("Math.floor(" + num + ")=" + Math.floor(num));   
    System.out.println("Math.round(" + num + ")=" + Math.round(num));   
    System.out.println("Math.ceil(" + num + ")=" + Math.ceil(num));   
  }   
}  
 

Running result

Math.floor(1.4)=1.0
Math.round(1.4)=1
Math.ceil(1.4)=2.0
Math.floor(1.5)=1.0
Math.round(1.5)=2
Math.ceil(1.5)=2.0
Math.floor(1.6)=1.0
Math.round(1.6)=2
Math.ceil(1.6)=2.0
Math.floor(-1.4)=-2.0
Math.round(-1.4)=-1
Math.ceil(-1.4)=-1.0
Math.floor(-1.5)=-2.0
Math.round(-1.5)=-1
Math.ceil(-1.5)=-1.0
Math.floor(-1.6)=-2.0
Math.round(-1.6)=-2
Math.ceil(-1.6)=-1.0


Related articles: