问题
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.
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
What I mean is that it would be numbers like these: 40, 42.5, 45, 47.5, 50
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?
回答1:
Do it as follows:
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;
}
}
Output:
12.5
15.0
12.5
10.0
Explanation:
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);
Output:
6.666666666666667
7
667
6.67
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
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
.
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
.
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
.
I hope, it is clear.
来源:https://stackoverflow.com/questions/60712200/how-to-round-to-2-5-in-java