java 中取整操作提供了四種方法:分別是:
public
static
double
ceil(
double
a)
//向上取整
|
|
第一種:ceil是天花板的意思,表示向上取整。 測試:
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
));
|
|
輸出結果:
2.0
-
1.0
2.0
-
1.0
|
|
第二種:floor是地板的意思,表示向下取整。 測試:
System.out.println(Math.floor(
1.01
));
|
|
輸出:
1.0
|
|
第三種:round執行的就是數學上的四舍五入運行。 查看它源碼可知其與floor方法的關系:
|
|
測試:
|
|
第四種:最有意思的,返回最接近參數的整數,如果有2個數同樣接近,則返回偶數的那個。它有兩個特殊的情況:
1)如果參數本身是整數,則返回本身。
2)如果不是數字或無窮大或正負0,則結果為其本身。
Returns the double value that is closest in value to the argument and is equal to a mathematical integer. If two double values that are mathematical integers are equally close, the result is the integer value that is even. Special cases:
If the argument value is already equal to a mathematical integer, then the result is the same as the argument.
If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument.
Parameters: a a double value.
Returns: the closest floating-point value to a that is equal to a mathematical integer.
測試:
|
|