有时候我需要将一个浮点数四舍五入到最接近的四分之一,有时候最接近的一半。如何将一个浮点数四舍五入到最接近的四分之一
对于半我用
Math.round(myFloat*2)/2f
我可以使用
Math.round(myFloat*4)/4f
。
但有没有其他建议?
有时候我需要将一个浮点数四舍五入到最接近的四分之一,有时候最接近的一半。如何将一个浮点数四舍五入到最接近的四分之一
对于半我用
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
怎么会解决两者兼而有之?它如何知道使用哪个? 'Math.round(3.8 * 4)/ 4f == 3.75' – 2011-03-24 12:49:10
@user unk:因为'一半是两个季度'和:http://download.oracle.com/javase/1.4.2/docs/api/ java/lang/Math.html#round(float)/ – 2011-03-24 12:53:38
但是'Math.round(3.8 * 2)/ 2f == 4.0',而不是'3.75'。 – 2011-03-24 12:59:23
从数学上讲,你可以用0.25乘以你的浮动,圆形,然后通过0.25又分为。
编辑:我很抱歉,似乎我误解了你的意思季度。不过,据我所知,这是最简单的四舍五入到小数位和度数的方法。
我认为你的意思是“乘以4”。 – DJClayworth 2011-03-24 13:47:03
(Math.round(num/toNearest))*toNearest;
将圆一个数字toNearest
我没有看到这个问题... – dagnelies 2011-03-24 13:01:37