Rounding up a number to nearest multiple of 5

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

    I've created a method that can convert a number to the nearest that will be passed in, maybe it will help to someone, because i saw a lot of ways here and it did not worked for me but this one did:

    /**
     * The method is rounding a number per the number and the nearest that will be passed in.
     * If the nearest is 5 - (63->65) | 10 - (124->120).
     * @param num - The number to round
     * @param nearest - The nearest number to round to (If the nearest is 5 -> (0 - 2.49 will round down) || (2.5-4.99 will round up))
     * @return Double - The rounded number
     */
    private Double round (double num, int nearest) {
        if (num % nearest >= nearest / 2) {
            num = num + ((num % nearest - nearest) * -1);
        } else if (num % nearest < nearest / 2) {
            num = num - (num % nearest);
        }
        return num;
    }
    

提交回复
热议问题