Rounding up a number to nearest multiple of 5

后端 未结 21 1905
感动是毒
感动是毒 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:04

    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.

    0 讨论(0)
  • 2020-11-27 16:04

    In case you only need to round whole numbers you can use this function:

    public static long roundTo(long value, long roundTo) {
        if (roundTo <= 0) {
            throw new IllegalArgumentException("Parameter 'roundTo' must be larger than 0");
        }
        long remainder = value % roundTo;
        if (Math.abs(remainder) < (roundTo / 2d)) {
            return value - remainder;
        } else {
            if (value > 0) {
                return value + (roundTo - Math.abs(remainder));
            } else {
                return value - (roundTo - Math.abs(remainder));
            }
        }
    }
    

    The advantage is that it uses integer arithmetics and works even for large long numbers where the floating point division will cause you problems.

    0 讨论(0)
  • 2020-11-27 16:05
    int roundUp(int n, int multipleOf)
    {
      int a = (n / multipleOf) * multipleOf;
      int b = a + multipleOf;
      return (n - a > b - n)? b : a;
    }
    

    source: https://www.geeksforgeeks.org/round-the-given-number-to-nearest-multiple-of-10/

    0 讨论(0)
  • 2020-11-27 16:08

    This Kotlin function rounds a given value 'x' to the closest multiple of 'n'

    fun roundXN(x: Long, n: Long): Long {
        require(n > 0) { "n(${n}) is not greater than 0."}
    
        return if (x >= 0)
            ((x + (n / 2.0)) / n).toLong() * n
        else
            ((x - (n / 2.0)) / n).toLong() * n
    }
    
    fun main() {
        println(roundXN(121,4))
    }
    

    Output: 120

    0 讨论(0)
  • 2020-11-27 16:10

    You can use this method Math.round(38/5) * 5 to get multiple of 5

    It can be replace with Math.ceil or Math.floor based on how you want to round off the number

    0 讨论(0)
  • 2020-11-27 16:11
    int round(int num) {
        int temp = num%5;
        if (temp<3)
             return num-temp;
        else
             return num+5-temp;
    }
    
    0 讨论(0)
提交回复
热议问题