Java 如何将浮标四舍五入到最近的四分之一

Java 如何将浮标四舍五入到最近的四分之一,java,math,rounding,Java,Math,Rounding,有时我需要将浮点数四舍五入到最近的四分之一,有时需要四舍五入到最近的一半 我用了一半 Math.round(myFloat*2)/2f 我可以用 Math.round(myFloat*4)/4f 但还有其他建议吗 您只需要: Math.round(myFloat*4)/4f 因为一半也是四分之二,所以这个单一的等式也会考虑到你的四舍五入。对于半舍五入或四分之一舍五入,不需要使用两个不同的方程式 代码示例: public class Main { public static void

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

我用了一半

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

从数学上讲,你可以将你的浮点数乘以.25,四舍五入,然后再除以.25

编辑:对不起,我好像误解了你所说的四分之一。然而,据我所知,这是将小数位数和度数四舍五入的最简单方法。

(Math.round(num/toNearest))*toNearest


将一个数字四舍五入到最高音

如何解决这两个问题?它如何知道使用哪一个
Math.round(3.8*4)/4f==3.75
@user unk:因为
一半是四分之二
和:但是
Math.round(3.8*2)/2f==4.0
,而不是
3.75
@user:试试
(3.8*4)/4f
,所以你的系数是4而不是2。(不确定系数在这种情况下是否是正确的术语。有更好的术语吗?)。在另一种情况下为0.5。你不能在一个方程中同时解这两个问题。我想你的意思是“乘以4”。