四舍五入
Math.round(f);
向上取整
(int) Math.round((f+0.5));
在Android Studio中测试一下(P.s.本人是Android开发)
Log.i(TAG, "Math.round测试:"+roundtest((float) 11.1,true)+","+roundtest((float) 11.1,false));
Log.i(TAG, "Math.round测试:"+roundtest((float) 11.6,true)+","+roundtest((float) 11.6,false));
Log.i(TAG, "Math.round测试:"+roundtest((float) 11.0,true)+","+roundtest((float) 11.0,false));
Log.i(TAG, "Math.round测试:"+roundtest((float) 11.5,true)+","+roundtest((float) 11.5,false));
//这是一个Math.round的测试(是否+0.5)
public static int roundtest(float f,boolean b) {
if (b){
return (int) Math.round((f+0.5));
}else {
return Math.round(f);
}
}
分别用11.1 11.6 11.0 11.5来测试
得到的结果为
第一列12为向上取整
第二列结果为四舍五入
符合
保留小数位的四舍五入
public static double round(double num,int scale){
return Math.round(num*Math.pow(10.0, scale))/Math.pow(10.0, scale);
}