如何将浮球舍入到最近的四分之一

Bic*_*ick 9 java math rounding

有时我需要将浮子绕到最近的四分之一,有时到最近的一半.

对于我使用的一半

Math.round(myFloat*2)/2f 
Run Code Online (Sandbox Code Playgroud)

我可以用

Math.round(myFloat*4)/4f.

但还有其他建议吗?

Pau*_*sik 28

所有你需要的是:

Math.round(myFloat*4)/4f
Run Code Online (Sandbox Code Playgroud)

由于一半也是两个季度,这个单一的等式也将照顾你的半舍入.对于半舍入或四分之一舍入,您不需要执行两个不同的等式.

代码示例:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

1.0
1.25
1.25
1.5
1.5
1.75
1.75
1.75
2.0
2.0
Run Code Online (Sandbox Code Playgroud)

  • 但是`Math.round(3.8*2)/ 2f == 4.0`,而不是`3.75`. (3认同)

cha*_*143 5

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

将数字舍入到 toNearest