Java Math.round(),Math.ceil(),Math.floor()的區(qū)別詳解
Math.round() “四舍五入”,
小數(shù)點后第一位<5
- 正數(shù):Math.round(11.46)=11
- 負數(shù):Math.round(-11.46)=-11
小數(shù)點后第一位>5
- 正數(shù):Math.round(11.68)=12
- 負數(shù):Math.round(-11.68)=-12
小數(shù)點后第一位=5
- 正數(shù):Math.round(11.5)=12
- 負數(shù):Math.round(-11.5)=-11
double d = 3.1415926; double d2 = 18.58; double d3 = -15.23; double d4 = -16.85; long round1 = Math.round(d); // 結(jié)果 3 long round2 = Math.round(d2); // 結(jié)果 19 long round3 = Math.round(d3); // 結(jié)果 -15 long round4 = Math.round(d4); // 結(jié)果 -17
Math.ceil() “向上取整”, 即小數(shù)部分直接舍去,并向正數(shù)部分進1
double d = 3.1415926; double d2 = 18.58; double d3 = -15.23; double d4 = -16.85; double d5 = -16.5; double d6 = 16.5; double ceil1 = Math.ceil(d); // 結(jié)果 4.0 double ceil2 = Math.ceil(d2); // 結(jié)果 19.0 double ceil3 = Math.ceil(d3); // 結(jié)果 -15.0 double ceil4 = Math.ceil(d4); // 結(jié)果 -16.0 double ceil5 = Math.ceil(d5); // 結(jié)果 -16.0 double ceil6 = Math.ceil(d6); // 結(jié)果 17.0
【注】該數(shù)為小數(shù)時,小數(shù)部分直接舍去
Math.floor() “向下取整” ,即小數(shù)部分直接舍去
double d = 3.1415926; double d2 = 18.58; double d3 = -15.23; double d4 = -16.85; double d5 = -16.5; double d6 = 16.5; double floor1 = Math.floor(d); // 結(jié)果 3.0 double floor2 = Math.floor(d2); // 結(jié)果 18.0 double floor3 = Math.floor(d3); // 結(jié)果 -16.0 double floor4 = Math.floor(d4); // 結(jié)果 -17.0 double floor5 = Math.floor(d5); // 結(jié)果 -17.0 double floor6 = Math.floor(d6); // 結(jié)果 16.0
【注】 Math.floor()容易出現(xiàn)精度問題,舉個最簡單例子:
對小數(shù) 8.54 保留兩位小數(shù)(雖然它已經(jīng)保留了 2 位小數(shù)):
Math.floor(8.54*100)/100 // 輸出結(jié)果為 8.53, 注意是 8.53 而不是 8.54。
所以這種函數(shù)慎用。
到此這篇關(guān)于Java Math.round(),Math.ceil(),Math.floor()的區(qū)別詳解的文章就介紹到這了,更多相關(guān)Math.round(),Math.ceil(),Math.floor()內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot使用Jasypt對YML文件配置內(nèi)容加密的方法(數(shù)據(jù)庫密碼加密)
本文介紹了如何在SpringBoot項目中使用Jasypt對application.yml文件中的敏感信息(如數(shù)據(jù)庫密碼)進行加密,通過引入Jasypt依賴、配置加密密鑰、加密敏感信息并測試解密功能,可以提高配置文件的安全性,減少因配置文件泄露導(dǎo)致的安全風(fēng)險,感興趣的朋友一起看看吧2025-03-03
SpringBoot+隨機鹽值+雙重MD5實現(xiàn)加密登錄
數(shù)據(jù)加密在很多項目上都可以用到,大部分都會采用MD5進行加密,本文主要介紹了SpringBoot+隨機鹽值+雙重MD5實現(xiàn)加密登錄,具有一定的參考價值,感興趣的可以了解一下2024-02-02
微服務(wù)如何通過feign.RequestInterceptor傳遞參數(shù)
這篇文章主要介紹了微服務(wù)如何通過feign.RequestInterceptor傳遞參數(shù),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03
SpringBoot整合Docker實現(xiàn)一次構(gòu)建到處運行的操作方法
本文講解的是 SpringBoot 引入容器化技術(shù) Docker 實現(xiàn)一次構(gòu)建到處運行,包括鏡像構(gòu)建、Docker倉庫搭建使用、Docker倉庫可視化UI等內(nèi)容,需要的朋友可以參考下2022-10-10
java 使用HttpURLConnection發(fā)送數(shù)據(jù)簡單實例
這篇文章主要介紹了java 使用HttpURLConnection發(fā)送數(shù)據(jù)簡單實例的相關(guān)資料,需要的朋友可以參考下2017-06-06

