2011-03-24 65 views

回答

24

所有你需要的是:

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 
+0

怎么会解决两者兼而有之?它如何知道使用哪个? 'Math.round(3.8 * 4)/ 4f == 3.75' – 2011-03-24 12:49:10

+0

@user unk:因为'一半是两个季度'和:http://download.oracle.com/javase/1.4.2/docs/api/ java/lang/Math.html#round(float)/ – 2011-03-24 12:53:38

+3

但是'Math.round(3.8 * 2)/ 2f == 4.0',而不是'3.75'。 – 2011-03-24 12:59:23

1

从数学上讲,你可以用0.25乘以你的浮动,圆形,然后通过0.25又分为。

编辑:我很抱歉,似乎我误解了你的意思季度。不过,据我所知,这是最简单的四舍五入到小数位和度数的方法。

+0

我认为你的意思是“乘以4”。 – DJClayworth 2011-03-24 13:47:03

5

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

将圆一个数字toNearest