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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5419123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 11:01:49  来源:igfitidea点击:

How to round a float to the nearest quarter

javamathrounding

提问by Bick

Sometimes I need to round a float to the nearest quarter and sometimes to the nearest half.

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

For the half I use

对于我使用的一半

Math.round(myFloat*2)/2f 

I can use

我可以用

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

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

but is there any other suggestions?

但还有其他建议吗?

回答by Paul Sasik

All you need is:

所有你需要的是:

Math.round(myFloat*4)/4f

Since a half is also two quarters this single equation will take care of your half-rounding as well. You don't need to do two different equations for half or quarter rounding.

由于一半也是四分之二,这个单一的等式也将处理你的半舍入。您不需要为二分之一或四分之一四舍五入做两个不同的方程。

Code Sample:

代码示例:

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);
    }
}

Output:

输出:

1.0
1.25
1.25
1.5
1.5
1.75
1.75
1.75
2.0
2.0

回答by chargers2143

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

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

Will round a number to toNearest

将一个数字四舍五入到 toNearest

回答by Shafique Arnab

Mathematically speaking, you could multiply your float by .25, round it, and then divide again by .25.

从数学上讲,您可以将浮点数乘以 0.25,四舍五入,然后再除以 0.25。

EDIT: I'm sorry, it seems I misunderstood what you meant by quarter. However, as far as I know, this is the simplest way to round to various decimal places and degrees.

编辑:对不起,我似乎误解了你所说的季度的意思。但是,据我所知,这是四舍五入到各种小数位和度数的最简单方法。