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)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
詳解基于spring多數(shù)據(jù)源動態(tài)調(diào)用及其事務處理
本篇文章主要介紹了基于spring多數(shù)據(jù)源動態(tài)調(diào)用及其事務處理 ,具有一定的參考價值,感興趣的小伙伴們可以參考一下
2017-06-06
MyBatis的<foreach>以及java代碼的批處理方式
這篇文章主要介紹了MyBatis的<foreach>以及java代碼的批處理方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
2024-08-08
解決SpringMVC Controller 接收頁面?zhèn)鬟f的中文參數(shù)出現(xiàn)亂碼的問題
下面小編就為大家分享一篇解決SpringMVC Controller 接收頁面?zhèn)鬟f的中文參數(shù)出現(xiàn)亂碼的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
2018-03-03
MyBatis中#{}?和?${}?的區(qū)別和動態(tài)?SQL詳解
這篇文章主要介紹了MyBatis中#{}和${}的區(qū)別,包括參數(shù)傳遞、安全性、性能等方面,然后詳細介紹了如何使用#{}和${}進行排序、模糊查詢、動態(tài)SQL、數(shù)據(jù)庫連接池等操作,最后,總結了注解方式的動態(tài)SQL,感興趣的朋友跟隨小編一起看看吧
2024-11-11 
