Java Math.round()函數小結


  Math類中提供了三個與取整有關的方法:ceil,floor,round,這些方法的作用於它們的英文名稱的含義相對應,例如:ceil的英文意義是天花板,該方法就表示向上取整,Math.ceil(11.3)的結果為12,Math.ceil(-11.6)的結果為-11;floor的英文是地板,該方法就表示向下取整,Math.floor(11.6)的結果是11,Math.floor(-11.4)的結果-12;最難掌握的是round方法,他表示“四舍五入”,算法為Math.floor(x+0.5),即將原來的數字加上0.5后再向下取整,所以,Math.round(11.5)的結果是12,Math.round(-11.5)的結果為-11.Math.round( )符合這樣的規律:小數點后大於5全部加,等於5正數加,小於5全不加。
讓我們看看JDK的說明:  
(1)public static long round(double a)  
returns the closest long to the argument. the result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long. in other words, the result is equal to the value of the expression:    
    
  (long)math.floor(a  +  0.5d)  

(2)public static double floor(double a)  
  returns the largest(closest to positive infinity) double value that is not greater than the argument and is equal to a mathematical integer.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 value.    
  returns:  
  the smallest (closest to negative infinity) floating-point value that is not less than the argument and is equal to a mathematical integer.

//import java.math.*;

public class RoundTest {

 

 

public static void main(String[] args) {

// TODO Auto-generated method stub

// Math.round():Java中的四舍五入函數

System.out.println("Case1:小數點后第一位 = 5");

System.out.println("正數:Math.round(11.5) = " + Math.round(11.5));

System.out.println("負數:Math.round(-11.5) = " + Math.round(-11.5));

 

System.out.println("Case2:小數點后第一位 < 5");

System.out.println("正數:Math.round(11.49) = " + Math.round(11.49));

System.out.println("負數:Math.round(-11.49) = " + Math.round(-11.49));

 

System.out.println("Case3:小數點后第一位 > 5");

System.out.println("正數:Math.round(11.69) = " + Math.round(11.69));

System.out.println("負數:Math.round(-11.69) = " + Math.round(-11.69));

 

System.out.println("結論:正數小數點后大於5則進位;負數小數點后小於以及等於5都舍去,大於5的則進位");

System.out.println("也就是說:小數點后大於5全部加,等於5正數加,小於5全不加");

}

}

 

Parameters
d the value to be rounded.
Returns
  • the closest integer to the argument. 


免責聲明!

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



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