There are four ways to take an integer operation in Java:
publicstatic double ceil(doublea)//向上取整
public static double floor(double a)//向下取整 public static long round(double a)//四舍五入取整 public static double rint(double a)//最近取整
The first type: Ceil is the meaning of the ceiling, which means rounding up. Test:
System.out.println(Math.ceil(1.01));System.out.println(Math.ceil(-1.01));System.out.println(Math.ceil(1.5));System.out.println(Math.ceil(-1.5));
Output Result:
2.0-1.02.0-1.0
The second type: floor is the meaning of flooring, which means rounding down. Test:
System.out.println(Math.floor(1.01));
System.out.println(Math.floor(-1.01));System.out.println(Math.floor(1.5));System.out.println(Math.floor(-1.5));
Output:
1.0
-2.01.0-2.0
The third type: round performs a mathematical rounding run. See the source of its relationship with the floor method:
public static long round(double a) {return (long)floor(a + 0.5d); }
Test:
System.out.println(Math.round(-1.5)); System.out.println(Math.round(1.5));结果:-12
The fourth type: Most interesting, returns the integer nearest the parameter, and returns the even if there are 2 numbers equally close to each other. It has two special cases:
1) If the argument itself is an integer, it returns itself.
2) If it is not a number or infinity or plus or minus 0, the result is itself.
Returns The double value, the closest in value to the argument, and is equal to a mathematical integer. If double values that is mathematical integers was equally close, the result is the integer value, which is even. Special cases:
If The argument value is already equal to a mathematical integer and then the result is the same as the argument.
If The argument is a NaN or an infinity or positive zero or negative zero and then the result is the same as the argument.
Parameters:a a double value.
Returns:the closest floating-point value to a, is equal to a mathematical integer.
Test:
System.out.println(Math.rint(-1.5));System.out.println(Math.rint(1.5));System.out.println(Math.rint(-2.5));System.out.println(Math.rint(2.5));结果:-2.02.0-2.02.0
Four methods of rounding in Java