Java中Math.round()的用法及說明
Math.round()的用法
遇到了關(guān)于Math.round()的用法的基礎(chǔ)題,發(fā)現(xiàn)自己還不是太熟悉,所以來總結(jié)一下。
Java中的Math.round()方法是將浮點(diǎn)型進(jìn)行“四舍五入”轉(zhuǎn)換為int類型的一個(gè)方法。
使用細(xì)節(jié)可以看例題
- 小數(shù)點(diǎn)后第一位等于五時(shí):
System.out.println(Math.round(-11.5)); -> 輸出為 -11 System.out.println(Math.round(11.5)); -> 輸出為 12
- 小數(shù)點(diǎn)后第一位小于五時(shí):
System.out.println(Math.round(-11.41)); -> 輸出為 -11 System.out.println(Math.round(11.41)); -> 輸出為 11
- 小數(shù)點(diǎn)后第一位大于五時(shí):
System.out.println(Math.round(-11.58)); -> 輸出為 -12 System.out.println(Math.round(11.58)); -> 輸出為 12
代碼驗(yàn)證
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)); } }
結(jié)果圖:
一句話結(jié)論:
將括號內(nèi)的數(shù) + 0.5 向下取整即為輸出。
驗(yàn)證結(jié)論
- 小數(shù)點(diǎn)后第一位等于五時(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ù)點(diǎn)后第一位小于五時(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ù)點(diǎn)后第一位大于五時(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
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

java短信驗(yàn)證碼獲取次數(shù)限制實(shí)例

Swagger異常定位紀(jì)實(shí)Swagger設(shè)計(jì)問題分析

詳解基于spring多數(shù)據(jù)源動態(tài)調(diào)用及其事務(wù)處理

MyBatis的<foreach>以及java代碼的批處理方式

解決SpringMVC Controller 接收頁面?zhèn)鬟f的中文參數(shù)出現(xiàn)亂碼的問題

MyBatis中#{}?和?${}?的區(qū)別和動態(tài)?SQL詳解