Java.lang.Math的round()方法返回的是整型,如果要保留小数位的话可以先乘以(小数位数 * 10),使用Java.lang.Math的round()方法计算之后再除以(小数位数 * 10)。

/***//**
*浮点数的四舍五入。
*@paramf代表源浮点数
*@paramdigits保留的小数点后位数
*@returnfloat
*/

publicstaticfloatround(floatf,intdigits)...{
floatoffset=1.0f;

if(digits==0)...{
offset=1.0f;

}elseif(digits>0)...{
offset=digits*10f;

}elseif(digits<0)...{
returnf;
}

f=java.lang.Math.round(f*offset)/offset;
returnf;
}

/***//**
*浮点数的四舍五入。
*@paramf代表源浮点数
*@paramdigits保留的小数点后位数
*@returnfloat
*/
publicstaticfloatround(floatf,intdigits)...{
floatoffset=1.0f;
if(digits==0)...{
offset=1.0f;
}elseif(digits>0)...{
offset=digits*10f;
}elseif(digits<0)...{
returnf;
}
f=java.lang.Math.round(f*offset)/offset;
returnf;
}
Java浮点数四舍五入
5500

被折叠的 条评论
为什么被折叠?



