Java中Math.round()的用法及說明
更新時間:2024年02月24日 15:38:46 作者:木木是木木
這篇文章主要介紹了Java中Math.round()的用法及說明,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
Math.round()的用法
遇到了關于Math.round()的用法的基礎題,發(fā)現(xiàn)自己還不是太熟悉,所以來總結一下。
Java中的Math.round()方法是將浮點型進行“四舍五入”轉換為int類型的一個方法。
使用細節(jié)可以看例題
- 小數(shù)點后第一位等于五時:
System.out.println(Math.round(-11.5)); -> 輸出為 -11 System.out.println(Math.round(11.5)); -> 輸出為 12
- 小數(shù)點后第一位小于五時:
System.out.println(Math.round(-11.41)); -> 輸出為 -11 System.out.println(Math.round(11.41)); -> 輸出為 11
- 小數(shù)點后第一位大于五時:
System.out.println(Math.round(-11.58)); -> 輸出為 -12 System.out.println(Math.round(11.58)); -> 輸出為 12
代碼驗證
public class main {
public static void main(String[] args) {
System.out.println(Math.round(-11.5));
System.out.println(Math.round(11.5));
System.out.println(Math.round(-11.41));
System.out.println(Math.round(11.41));
System.out.println(Math.round(-11.58));
System.out.println(Math.round(11.58));
}
}
結果圖:

一句話結論:
將括號內(nèi)的數(shù) + 0.5 向下取整即為輸出。
驗證結論
- 小數(shù)點后第一位等于五時:
System.out.println(Math.round(-11.5)); -> -11.5 + 0.5 = -11 向下取整輸出為 -11 System.out.println(Math.round(11.5)); -> 11.5 + 0.5 = 12 向下取整輸出為 12
- 小數(shù)點后第一位小于五時:
System.out.println(Math.round(-11.41)); -> -11.41 + 0.5 = -10.91 向下取整輸出為 -11 System.out.println(Math.round(11.41)); -> 11.41 + 0.5 = 11.91 向下取整輸出為 11
- 小數(shù)點后第一位大于五時:
System.out.println(Math.round(-11.58)); -> -11.58 + 0.5 = -11.08 向下取整輸出為 -12 System.out.println(Math.round(11.58)); -> 11.58 + 0.5 = 12.05 向下取整輸出為 12
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
使用Springboot實現(xiàn)獲取某個城市當天的天氣預報
這篇文章主要為大家詳細介紹了使用Springboot實現(xiàn)獲取某個城市當天的天氣預報的相關知識,感興趣的小伙伴可以跟隨小編一起學習一下2024-04-04
java自定義任務類定時執(zhí)行任務示例 callable和future接口使用方法
Callable是類似于Runnable的接口,實現(xiàn)Callable接口的類和實現(xiàn)Runnable的類都是可被其它線程執(zhí)行的任務2014-01-01
利用SpringBoot實現(xiàn)多數(shù)據(jù)源的兩種方式總結
關于動態(tài)數(shù)據(jù)源的切換的方案有很多,核心只有兩種,一種是構建多套環(huán)境,另一種是基于spring原生的AbstractRoutingDataSource切換,這篇文章主要給大家介紹了關于利用SpringBoot實現(xiàn)多數(shù)據(jù)源的兩種方式,需要的朋友可以參考下2021-10-10
java中四種生成和解析XML文檔的方法詳解(介紹+優(yōu)缺點比較+示例)
本篇文章主要介紹了四種生成和解析XML文檔的方法,即:DOM、SAX、JDOM和DOM4J,具有一定的參考價值,有興趣的可以了解一下。2016-11-11

