Java Math.round函數(shù)詳解
1.代碼如下:
public class TestMathRound {
public static void main(String[] args) {
System.out.println("小數(shù)點后第一位=5");
System.out.println("正數(shù):Math.round(11.5)=" + Math.round(11.5));//12
System.out.println("負數(shù):Math.round(-11.5)=" + Math.round(-11.5));//-11
System.out.println();
System.out.println("小數(shù)點后第一位<5");
System.out.println("正數(shù):Math.round(11.46)=" + Math.round(11.46));//11
System.out.println("負數(shù):Math.round(-11.46)=" + Math.round(-11.46));//-11
System.out.println();
System.out.println("小數(shù)點后第一位>5");
System.out.println("正數(shù):Math.round(11.68)=" + Math.round(11.68));//12
System.out.println("負數(shù):Math.round(-11.68)=" + Math.round(-11.68));//-12
}
}
2.結果如下,可以自己運行。

3.本來以為是四舍五入,取最靠近的整數(shù),查了網(wǎng)上說有四舍六入五成雙,最后還不如看源碼。源碼如下:
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ù)會默認加0.5,之后調(diào)用floor函數(shù),然后返回。floor函數(shù)可以理解為向下取整。

4.綜上,Math.round函數(shù)是默認加上0.5之后,向下取整。
到此這篇關于Java Math.round函數(shù)詳解的文章就介紹到這了,更多相關Java Math.round函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
解決IDEA報錯war?exploded?is?not?valid問題
在使用IntelliJ?IDEA時遇到'[projectname]warexploded'無效的問題,可以通過清除項目列表、重新導入項目和配置新的Tomcat來解決,確保在Tomcat配置中,將ApplicationContext修改為僅包含一個'/',這一方法或許能幫助遇到相似問題的開發(fā)者2024-09-09
如何在Spring WebFlux的任何地方獲取Request對象
這篇文章主要介紹了如何在Spring WebFlux的任何地方獲取Request對象,幫助大家更好的理解和使用springboot框架,感興趣的朋友可以了解下2021-01-01
idea查看properties中文變成unicode碼的解決方案
這篇文章主要介紹了idea查看properties中文變成unicode碼的解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06
用Spring Native將SpringBoot程序轉換為GraalVM
這篇文章主要介紹了用Spring Native將SpringBoot程序轉換為GraalVM的方法,幫助大家更好的理解和學習使用SpringBoot,感興趣的朋友可以了解下2021-04-04

