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. PHP中Session會(huì)話的使用和分析2. 10個(gè)提供免費(fèi)PHP腳本下載的網(wǎng)站3. python 爬取嗶哩嗶哩up主信息和投稿視頻4. php5.6不能擴(kuò)展redis.so的解決方法5. Java 基于UDP協(xié)議實(shí)現(xiàn)消息發(fā)送6. PHP擴(kuò)展之APC——Alternative PHP Cache(可選PHP緩存)7. js實(shí)現(xiàn)跳一跳小游戲8. PHP設(shè)計(jì)模式(四)原型模式Prototype實(shí)例詳解【創(chuàng)建型】9. SpringBoot 開發(fā)提速神器 Lombok+MybatisPlus+SwaggerUI10. Python編寫nmap掃描工具
