2011-03-24 61 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