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.