What are the rounding rules in Java?

In Java, the rules for rounding are as follows:

  1. If rounding is applied to the integer, the result will remain unchanged.
  2. There are several ways to round a floating point number.
  3. Round down (the largest integer less than or equal to the number): use the Math.floor() function.
  4. Round up (take the smallest integer greater than or equal to the number): use the Math.ceil() function.
  5. Round to the nearest whole number: use the Math.round() function.
  6. Round towards zero (round to the nearest integer towards zero, discard the decimal portion): use type conversion or typecasting (int).

For example:

int num1 = 10;
double num2 = 3.14;

System.out.println(Math.floor(num2)); // 输出 3.0
System.out.println(Math.ceil(num2));  // 输出 4.0
System.out.println(Math.round(num2)); // 输出 3
System.out.println((int) num2);       // 输出 3
bannerAds