如何在 Java 中舍入到 2.5? [英] How to round to 2.5 in Java?
问题描述
所以我正在为 android 制作一个健身应用程序,现在我要求用户输入一个数字,例如72.5
So I am making a fitness app for android and now I am asking the user to input a number e.g. 72.5
我会取这个数字并取其百分比并将函数应用于此等.
I would take this number and take percentages of it and apply functions to this etc.
我需要确保我在该数字中所占的百分比四舍五入为 2.5.这是因为在英国健身房你只有以下盘子: 1.25x2=2.5 2.5x2=5 5+2.5=7.5 , 10, 15, 20, 25
I need to make sure that the percentage I take of that number is rounded to 2.5. This is because in a UK gym you only have the following plates: 1.25x2=2.5 2.5x2=5 5+2.5=7.5 , 10, 15, 20, 25
我的意思是它会是这样的数字:40, 42.5, 45, 47.5, 50
What I mean is that it would be numbers like these: 40, 42.5, 45, 47.5, 50
如何将数字 N 舍入到最接近的 2.5?我知道 math.Round() 四舍五入到最接近的整数,但是像这样的自定义数字呢?
How can I round a Number N to the nearest 2.5? I understand that math.Round() rounds to nearest whole but what about to a custom number like this?
推荐答案
请按以下步骤操作:
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
说明:
下面的例子会更容易理解:
It will be easier to understand with the following example:
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.0
返回 7
(这是将 0.5
添加到 20 后的下限值/3.0
. 检查 this 以了解实现).但是,如果您想将其四舍五入到最近的 1/100
位(即最多 2
个小数位),一种更简单的方法(但不是那么精确.检查这更精确的方法)将四舍五入n * 100.0
(这将使它成为667
)然后除以100.0
> 这将给出 6.67(即最多 2 个小数位).注意 1/(1/100.0) = 100.0
As you can see here, rounding 20 / 3.0
returns 7
(which is the floor value after adding 0.5
to 20 / 3.0
. Check this to understand the implementation). However, if you wanted to round it up to the nearest 1/100
th place (i.e. up to 2
decimal places), an easier way (but not so precise. Check this for more precise way) would be to round n * 100.0
(which would make it 667
) and then divide it by 100.0
which would give 6.67 (i.e. up to 2 decimal places). Note that 1 / (1 / 100.0) = 100.0
同样,要将数字四舍五入到最近的 2.5
位,您需要对 1/2.5 = 0.4
做同样的事情,即 Math.round(n * 0.4)/0.4
.
Similarly, to round the number to the nearest 2.5
th place, you will need to do the same thing with 1 / 2.5 = 0.4
i.e. Math.round(n * 0.4) / 0.4
.
要将数字四舍五入到最近的 100
位,您需要对 1/100 = 0.01
执行相同的操作,即 Math.round(n * 0.1)/0.1
.
To round a number to the nearest 100
th place, you will need to do the same thing with 1 / 100 = 0.01
i.e. Math.round(n * 0.1) / 0.1
.
要将数字四舍五入到最近的 0.5
位,您需要对 1/0.5 = 2.0
执行相同的操作,即 Math.round(n * 2.0)/2.0
.
To round a number to the nearest 0.5
th place, you will need to do the same thing with 1 / 0.5 = 2.0
i.e. Math.round(n * 2.0) / 2.0
.
我希望很清楚.
这篇关于如何在 Java 中舍入到 2.5?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!