Java中的小數位的相關操作


整理一些基礎知識回顧的小知識,如有打擾還請見諒。

API文檔中的方法聲明

1. public static double ceil(double a):返回大於或等於參數的最小(最接近負無窮大) double值,並等於數學整數。 特殊情況:

  • 如果參數值已經等於數學整數,則結果與參數相同。

  • 如果參數爲NaN或無窮大或正零或負零,則結果與參數相同。

  • 如果參數值小於零但大於-1.0,則結果爲負零。

    需要注意的是價值Math.ceil(x)正是價值-Math.floor(-x) 。

2. public static double floor(double a):返回小於或等於參數的最大(最接近正無窮大) double值,等於數學整數。 特殊情況:

  • 如果參數值已經等於數學整數,則結果與參數相同。
  • 如果參數爲NaN或無窮大或正零或負零,則結果與參數相同。

3. public static double rint(double a):返回與參數最接近值的double值,等於數學整數。 如果作爲數學整數的兩個double值同樣接近,則結果爲均勻的整數值。 特殊情況:

  • 如果參數值已經等於數學整數,則結果與參數相同。
  • 如果參數爲NaN或無窮大或正零或負零,則結果與參數相同。

4. public static long round(double a):返回參數中最接近的long ,其中long四捨五入爲正無窮大。
特殊情況:

  • 如果參數是NaN,結果爲0。
  • 如果參數爲負無窮大或小於或等於Long.MIN_VALUE的值,則結果等於Long.MIN_VALUE的值。
  • 如果參數爲正無窮大或大於或等於Long.MAX_VALUE的值,則結果等於Long.MAX_VALUE的值。

5. public static int round(float a):返回參數最接近的int ,其中int四捨五入爲正無窮大。
特殊情況:

  • 如果參數是NaN,結果爲0。
  • 如果參數爲負無窮大或小於或等於Integer.MIN_VALUE的值,則結果等於Integer.MIN_VALUE的值。
  • 如果參數爲正無窮大或大於或等於Integer.MAX_VALUE的值,則結果等於Integer.MAX_VALUE的值。

程序運行結果

先附上程序的運行結果,不妨根據結果中所顯示的思考一下對應的方法。

2.3向上取整ceil:3.0
2.3向下取整floor:2.0
*******************
2.49四捨五入rint:2.0
2.50四捨五入rint:2.0
2.51四捨五入rint:3.0
*******************
2.4四捨五入round:2
2.5四捨五入round:3
2.6四捨五入round:3

代碼解析


        double num1 = 2.2;
        double num2 = 2.49;
        double num3 = 2.50;
        double num4 = 2.51;

        System.out.println("2.3向上取整ceil:"+Math.ceil(num1));
        System.out.println("2.3向下取整floor:"+Math.floor(num1));
        System.out.println("*******************");
        System.out.println("2.49四捨五入rint:"+Math.rint(num2));
        System.out.println("2.50四捨五入rint:"+Math.rint(num3));
        System.out.println("2.51四捨五入rint:"+Math.rint(num4));
        System.out.println("*******************");
        System.out.println("2.49四捨五入round:"+Math.round(num2));
        System.out.println("2.50四捨五入round:"+Math.round(num3));
        System.out.println("2.51四捨五入round:"+Math.round(num4));
        

小結:

  1. 向上取整cei()和向下取整floor()兩個方法與數學思想上的處理結果一致。
  2. rint()方法是將小數部分大於0.5的情況纔會產生進位。
  3. round()方法是將小數部分大於等於0.5的情況纔會產生進位。

當處理的數據爲負數的情況

-2.3向上取整ceil:-2.0
-2.3向下取整floor:-3.0
*******************
-2.49四捨五入rint:-2.0
-2.50四捨五入rint:-2.0
-2.51四捨五入rint:-3.0
*******************
-2.49四捨五入round:-2
-2.50四捨五入round:-2
-2.51四捨五入round:-3

結果清晰明瞭。
rint()和round()都是將小數部分大於等於-0.5的整數加一

發佈了45 篇原創文章 · 獲贊 47 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章