Rounding up a number to nearest multiple of 5

98,348

Solution 1

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.

Solution 2

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.

Solution 3

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

Solution 4

int roundUp(int num) {
    return (int) (Math.ceil(num / 5d) * 5);
}

Solution 5

int round(int num) {
    int temp = num%5;
    if (temp<3)
         return num-temp;
    else
         return num+5-temp;
}
Share:
98,348
Daniel Cook
Author by

Daniel Cook

Updated on June 23, 2021

Comments

  • Daniel Cook
    Daniel Cook almost 3 years

    Does anyone know how to round up a number to its nearest multiple of 5? I found an algorithm to round it to the nearest multiple of 10 but I can't find this one.

    This does it for ten.

    double number = Math.round((len + 5)/ 10.0) * 10.0;