Java Math.round函數(shù)詳解
1.代碼如下:
public class TestMathRound { public static void main(String[] args) {System.out.println('小數(shù)點(diǎn)后第一位=5');System.out.println('正數(shù):Math.round(11.5)=' + Math.round(11.5));//12System.out.println('負(fù)數(shù):Math.round(-11.5)=' + Math.round(-11.5));//-11System.out.println();System.out.println('小數(shù)點(diǎn)后第一位<5');System.out.println('正數(shù):Math.round(11.46)=' + Math.round(11.46));//11System.out.println('負(fù)數(shù):Math.round(-11.46)=' + Math.round(-11.46));//-11System.out.println();System.out.println('小數(shù)點(diǎn)后第一位>5');System.out.println('正數(shù):Math.round(11.68)=' + Math.round(11.68));//12System.out.println('負(fù)數(shù):Math.round(-11.68)=' + Math.round(-11.68));//-12 }}
2.結(jié)果如下,可以自己運(yùn)行。
3.本來(lái)以為是四舍五入,取最靠近的整數(shù),查了網(wǎng)上說(shuō)有四舍六入五成雙,最后還不如看源碼。源碼如下:
public static long round(double a) {if (a != 0x1.fffffffffffffp-2) // greatest double value less than 0.5 return (long)floor(a + 0.5d);else return 0; }
我們看到round函數(shù)會(huì)默認(rèn)加0.5,之后調(diào)用floor函數(shù),然后返回。floor函數(shù)可以理解為向下取整。
4.綜上,Math.round函數(shù)是默認(rèn)加上0.5之后,向下取整。
到此這篇關(guān)于Java Math.round函數(shù)詳解的文章就介紹到這了,更多相關(guān)Java Math.round函數(shù)內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 在A(yíng)ndroid中使用WebSocket實(shí)現(xiàn)消息通信的方法詳解2. python matplotlib:plt.scatter() 大小和顏色參數(shù)詳解3. Yii2.0引入CSS,JS文件方法4. JSP數(shù)據(jù)交互實(shí)現(xiàn)過(guò)程解析5. Python importlib動(dòng)態(tài)導(dǎo)入模塊實(shí)現(xiàn)代碼6. vue使用webSocket更新實(shí)時(shí)天氣的方法7. 淺談python出錯(cuò)時(shí)traceback的解讀8. android studio 打包自動(dòng)生成版本號(hào)與日期,apk輸入路徑詳解9. Nginx+php配置文件及原理解析10. JavaMail 1.4 發(fā)布
