關於java Math.round(Double a) 方法

首先看看API中關於這個方法怎麼說的,Math.round(Double a) Returns the closest long to the argument,意思就是返回最接近參數的long,實際上這樣沒法理解,比如有Math.round(7.5),那麼到底是返回8呢還是7呢?再如Math.round(-7.5)結果又會怎麼樣呢?

由此我寫了一些測試代碼並如下:

public class Test {
	public static void main(String[] args) {
		// 小數點後第一位 = 5
		System.out.println("正數:Math.round(11.5) = " + Math.round(11.5));
		System.out.println("負數:Math.round(-11.5) = " + Math.round(-11.5));
		
		// 小數點後第一位 < 5
		System.out.println("正數:Math.round(11.49) = " + Math.round(11.49));
		System.out.println("負數:Math.round(-11.49) = " + Math.round(-11.49));
		
		// 小數點後第一位 > 5
		System.out.println("正數:Math.round(11.69) = " + Math.round(11.69));
		System.out.println("負數:Math.round(-11.61) = " + Math.round(-11.69));
		
	}

}

打印結果如下:

正數:Math.round(11.5) = 12
負數:Math.round(-11.5) = -11
正數:Math.round(11.49) = 11
負數:Math.round(-11.49) = -11
正數:Math.round(11.69) = 12
負數:Math.round(-11.61) = -12

由此基本上可以得出結論:正數小數點後大於5則舍入,負數小數點後小於以及等於5都捨去,反之舍入,也可以說小數點後大於5全部加,等於5正數加,小於5全不加



發佈了21 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章