What are the rounding rules in Java?
In Java, the rules for rounding are as follows:
- If rounding is applied to the integer, the result will remain unchanged.
- There are several ways to round a floating point number.
- Round down (the largest integer less than or equal to the number): use the Math.floor() function.
- Round up (take the smallest integer greater than or equal to the number): use the Math.ceil() function.
- Round to the nearest whole number: use the Math.round() function.
- 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