Rounding up a number to nearest multiple of 5

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

    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.

提交回复
热议问题