如何将浮点数四舍五入到最接近的四分之一位。

10

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

对于半,我使用以下代码:

Math.round(myFloat*2)/2f 
我可以使用 Math.round(myFloat*4)/4f,但是否有其他建议?
3个回答

30

你所需要的只有:

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

@user 未知:因为一半等于两个四分之一,并且:http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Math.html#round(float)/ - Paul Sasik
4
但是 Math.round (3.8*2)/2f == 4.0,而不是 3.75 - user unknown
1
@user: 尝试使用(3.8*4)/4f,这样你的系数就是4,而不是使用2。(不确定系数在这种情况下是否是正确的术语。有更好的术语吗?) - Paul Sasik
是的,但你不是写过“您不需要为半舍入或四舍五入做两个不同的方程式”吗?那你的意思是什么? - user unknown
1
好的,在一个地方我想把0.74四舍五入到0.75。在另一个地方是到0.5。你不能用一个等式解决这两个问题。 - Bick
显示剩余2条评论

5

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

这段代码将会把一个数字四舍五入到最接近的 toNearest


1
数学上来说,你可以将浮点数乘以0.25,四舍五入,然后再除以0.25。
编辑:对不起,看来我误解了你所说的quarter的意思。然而,据我所知,这是最简单的四舍五入到不同小数位和度数的方法。

1
我想你的意思是“乘以4”。 - DJClayworth

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接