Rounding up a number to nearest multiple of 5
To round to the nearest of any value
int round(double i, int v){
return Math.round(i/v) * v;
}
You can also replace Math.round()
with either Math.floor()
or Math.ceil()
to make it always round down or always round up.
int roundUp(int num) {
return (int) (Math.ceil(num / 5d) * 5);
}
I think I have it, thanks to Amir
double round( double num, int multipleOf) {
return Math.floor((num + multipleOf/2) / multipleOf) * multipleOf;
}
Here's the code I ran
class Round {
public static void main(String[] args){
System.out.println("3.5 round to 5: " + Round.round(3.5, 5));
System.out.println("12 round to 6: " + Round.round(12, 6));
System.out.println("11 round to 7: "+ Round.round(11, 7));
System.out.println("5 round to 2: " + Round.round(5, 2));
System.out.println("6.2 round to 2: " + Round.round(6.2, 2));
}
public static double round(double num, int multipleOf) {
return Math.floor((num + (double)multipleOf / 2) / multipleOf) * multipleOf;
}
}
And here's the output
3.5 round to 5: 5.0
12 round to 6: 12.0
11 round to 7: 14.0
5 round to 2: 6.0
6.2 round to 2: 6.0
int roundUp(int n) {
return (n + 4) / 5 * 5;
}
Note - YankeeWhiskey's answer is rounding to the closest multiple, this is rounding up. Needs a modification if you need it to work for negative numbers. Note that integer division followed by integer multiplication of the same number is the way to round down.