java的四種取整方法

java的四種取整方法html

java 中取整操做提供了四種方法:分別是: java

public static double ceil(double a)//向上取整測試

 

 

 第一種:ceil是天花板的意思,表示向上取整。   測試: spa

System.out.println(Math.ceil(1.01));code

System.out.println(Math.ceil(-1.01));htm

System.out.println(Math.ceil(1.5));blog

System.out.println(Math.ceil(-1.5));ci

 

 

輸出結果: get

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.  

相關文章
相關標籤/搜索