Java round() 方法
round() 方法返回一個最接近的 int、long 型值,四捨五入。
round 表示"四捨五入",演算法為Math.floor(x+0.5) ,即將原來的數字加上 0.5 後再向下取整,所以 Math.round(11.5) 的結果為 12,Math.round(-11.5) 的結果為 -11。
語法
該方法有以下幾種語法格式:
long round(double d) int round(float f)
參數
d -- double 或 float 的原生數據類型
f -- float 原生數據類型
返回值
返回一個最接近的int、long型值,方法會指定返回的數據類型。
實例
實例
public class Test{
public static void main(String args[]){
double d = 100.675;
double e = 100.500;
float f = 100;
float g = 90f;
System.out.println(Math.round(d));
System.out.println(Math.round(e));
System.out.println(Math.round(f));
System.out.println(Math.round(g));
}
}
編譯以上程式,輸出結果為:
101 101 100 90