1. 程式人生 > >Java中Math.round()方法原理解讀

Java中Math.round()方法原理解讀

Java中Math.round()方法是將浮點數“四捨五入”轉換成整數的方法,但這裡的“四捨五入”和數學中的四捨五入有點差別,接下來就來解析一下在Java裡的原理。 1、首先直接上測試程式碼: public static void main(String[] args) { System.out.println(Math.round(12.4)); System.out.println(Math.round(12.5)); System.out.println(Math.round(12.9)); System.out.println(Math.round(-12.4)); System.out.println(Math.round(-12.5)); System.out.println(Math.round(-12.9)); } 執行結果: 12 13 13 -12 -12 -13 在沒有弄清原理之前,憑我自己猜想,我一直認為數字按照向0靠攏的思想,但結果表明我的猜想是錯誤的。 2、原始碼解析 看Math.round()內的實現,但JDK1.8內程式碼有點多(不知道其他版本的是怎樣的),但其真正的意思也就是如下: public static int round(float a) { return (int)floor(a + 0.5f); }

public static long round(double a) { return (long)floor(a + 0.5d); } 看到有兩個過載的方法,一個接收float型別返回int型別,另一個接收double型別返回long型別,這也很好理解,float和int都是佔4個位元組,double和long佔8個位元組,這樣精度就沒有丟失。但平時使用的時候還是要注意,因為實際應用中最常用double和int,所以可能需要轉換。 1)從上面的兩個方法可以看出,都是對數字加0.5後在再floor()方法 2)floo()方法的原理:取小於等於引數的最大整數浮點數(可以理解為向下取整數浮點數),如floor(12.5)=12.0,floor(12.9)=12.0,floor(-12.5)=-13.0,floor(-12.9)=-13.0。 3、結論 Math中的round方法,求的值就是取小於等於(引數+0.5)的最大整數。 本文是轉載的,僅供自己觀看!