Rounding up a number to nearest multiple of 5

后端 未结 21 1985
感动是毒
感动是毒 2020-11-27 15:24

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.

T

21条回答
  •  一整个雨季
    2020-11-27 16:14

    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.

提交回复
热议问题