如何舍入浮点数但将其保持浮点数(即不将其转换为 int)



例如,我有一个圆面积= 4.3的结果,我的问题是'当我得到的数字刨丝器超过.5[例如(4.6, 4.7, 4.8, 4.9(]时,我希望它给我5.0,但如果小于.5 [4.4, 4.3, 4.2, 4.1],那么给我4.0'

我尝试了Math.round()但它像 [4] 一样将 float 转换为 int,但我不想将其转换为 int

有没有办法做到这一点?

这是我的代码:

private float radius;
private double result;
public void show(float x)
{
    this.radius = x;
    this.result=Math.pow(x,2)*Math.PI;
    System.out.println("result is: "+result);
}

显然,我希望在一个函数中同时使用方法(Math.floor(((和(Math.ceil(((谢谢

Math.rint可能最接近您要查找的内容。请注意,它四舍五入为偶数。

最新更新