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. 使用IDEA編寫(xiě)jsp時(shí)EL表達(dá)式不起作用的問(wèn)題及解決方法2. idea自定義快捷鍵的方法步驟3. idea設(shè)置代碼格式化的方法步驟4. Docker容器如何更新打包并上傳到阿里云5. 刪除docker里建立容器的操作方法6. IntelliJ IDEA導(dǎo)出項(xiàng)目的方法7. Django中如何使用Channels功能8. IntelliJ IDEA設(shè)置編碼格式的方法9. Docker究竟是什么 為什么這么流行 它的優(yōu)點(diǎn)和缺陷有哪些?10. IntelliJ IDEA設(shè)置條件斷點(diǎn)的方法步驟

網(wǎng)公網(wǎng)安備