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
その他の拡張
Java Number クラス