有时我需要将浮点数四舍五入到最近的四分之一,有时又四舍五入到最近的一半。

我用了一半

Math.round(myFloat*2)/2f

我可以用
Math.round(myFloat*4)/4f

但是还有其他建议吗?

最佳答案

所有你需要的是:

Math.round(myFloat*4)/4f

由于一半也等于四分之一,因此这个方程式也可以解决您的半个四舍五入问题。您无需为半或四分之一四舍五入做两个不同的方程式。

代码样例:
public class Main {
    public static void main(String[] args) {
        float coeff = 4f;
        System.out.println(Math.round(1.10*coeff)/coeff);
        System.out.println(Math.round(1.20*coeff)/coeff);
        System.out.println(Math.round(1.33*coeff)/coeff);
        System.out.println(Math.round(1.44*coeff)/coeff);
        System.out.println(Math.round(1.55*coeff)/coeff);
        System.out.println(Math.round(1.66*coeff)/coeff);
        System.out.println(Math.round(1.75*coeff)/coeff);
        System.out.println(Math.round(1.77*coeff)/coeff);
        System.out.println(Math.round(1.88*coeff)/coeff);
        System.out.println(Math.round(1.99*coeff)/coeff);
    }
}

输出:
1.0
1.25
1.25
1.5
1.5
1.75
1.75
1.75
2.0
2.0

关于java - 如何将浮点数舍入到最近的四分之一,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5419123/

10-10 09:31