java的四種取整方法


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

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

  public static double floor( double a) //向下取整
  public static long round( double a) //四舍五入取整
  public static double rint( 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));

System.out.println(Math.floor(- 1.01 ));
System.out.println(Math.floor( 1.5 ));
System.out.println(Math.floor(- 1.5 ));
 
 

 輸出: 

1.0

- 2.0
1.0
- 2.0
 
 

 第三種:round執行的就是數學上的四舍五入運行。   查看它源碼可知其與floor方法的關系: 

public static long round( double a) {
return ( long )floor(a + 0 .5d);
     }
 
 

測試: 

System.out.println(Math.round(- 1.5 ));
System.out.println(Math.round( 1.5 ));
結果:
- 1
2
 
 

第四種:最有意思的,返回最接近參數的整數,如果有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. 
測試: 

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.0
2.0
- 2.0
2.0
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM