如何在 Java 中四舍五入到 2.5?

How to round to 2.5 in Java?

所以我正在为 android 制作一个健身应用程序,现在我要求用户输入一个数字,例如72.5

我会取这个数字并取其百分比并将函数应用于此等。

我需要确保我占该数字的百分比四舍五入为 2.5。这是因为在英国健身房,您只有以下板块: 1.25x2=2.5 2.5x2=5 5+2.5=7.5 , 10, 15, 20, 25

我的意思是应该是这样的数字:40、42.5、45、47.5、50

如何将数字 N 舍入到最接近的 2.5?我知道 math.Round() 四舍五入到最接近的整数,但是像这样的自定义数字呢?

按如下操作:

public class Main {
    public static void main(String args[]) {
        // Tests
        System.out.println(roundToNearest2Point5(12));
        System.out.println(roundToNearest2Point5(14));
        System.out.println(roundToNearest2Point5(13));
        System.out.println(roundToNearest2Point5(11));
    }

    static double roundToNearest2Point5(double n) {
        return Math.round(n * 0.4) / 0.4;
    }
}

输出:

12.5
15.0
12.5
10.0

解释:

下面的例子会更容易理解:

double n = 20 / 3.0;
System.out.println(n);
System.out.println(Math.round(n));
System.out.println(Math.round(n * 100.0));
System.out.println(Math.round(n * 100.0) / 100.0);

输出:

6.666666666666667
7
667
6.67

这里可以看到,四舍五入20 / 3.0returns7(也就是[=14=加上0.5后的底值)。勾选this to understand the implementation). However, if you wanted to round it up to the nearest 1/100th place (i.e. up to 2 decimal places), an easier way (but not so precise. Check 更精确的方法)将是四舍五入 n * 100.0(这将使它成为 667),然后将它除以 100.0,这将得到 6.67(即最多 2 位小数) .请注意 1 / (1 / 100.0) = 100.0

同样,要将数字四舍五入到最接近的第 2.5 位,您需要对 1 / 2.5 = 0.4 做同样的事情,即 Math.round(n * 0.4) / 0.4.

要将数字四舍五入到最接近的第 100 位,您需要对 1 / 100 = 0.01 做同样的事情,即 Math.round(n * 0.1) / 0.1.

要将数字四舍五入到最接近的第 0.5 位,您需要对 1 / 0.5 = 2.0 做同样的事情,即 Math.round(n * 2.0) / 2.0.

我希望,很清楚。

晚回复但你也可以做 2.5*(Math.round(number/2.5)) 同样的方法,如果你想以磅为单位四舍五入到最接近的第 5 位 5*(Math.round(number/5))