Rounding up a number to nearest multiple of 5

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

    Round a given number to the nearest multiple of 5.

    public static int round(int n)
      while (n % 5 != 0) n++;
      return n; 
    }
    
    0 讨论(0)
  • 2020-11-27 16:28

    CODE:

        public class MyMath
        {
            public static void main(String[] args) {
                runTests();
            }
            public static double myFloor(double num, double multipleOf) {
                return ( Math.floor(num / multipleOf) * multipleOf );
            }
            public static double myCeil (double num, double multipleOf) {
                return ( Math.ceil (num / multipleOf) * multipleOf );
            }
    
            private static void runTests() {
                System.out.println("myFloor (57.3,  0.1) : " + myFloor(57.3, 0.1));
                System.out.println("myCeil  (57.3,  0.1) : " + myCeil (57.3, 0.1));
                System.out.println("");
                System.out.println("myFloor (57.3,  1.0) : " + myFloor(57.3, 1.0));
                System.out.println("myCeil  (57.3,  1.0) : " + myCeil (57.3, 1.0));
                System.out.println("");
                System.out.println("myFloor (57.3,  5.0) : " + myFloor(57.3, 5.0));
                System.out.println("myCeil  (57.3,  5.0) : " + myCeil (57.3, 5.0));
                System.out.println("");
                System.out.println("myFloor (57.3, 10.0) : " + myFloor(57.3,10.0));
                System.out.println("myCeil  (57.3, 10.0) : " + myCeil (57.3,10.0));
            }
        }
    

    OUTPUT:There is a bug in the myCeil for multiples of 0.1 too ... no idea why.

        myFloor (57.3,  0.1) : 57.2
        myCeil  (57.3,  0.1) : 57.300000000000004
    
        myFloor (57.3,  1.0) : 57.0
        myCeil  (57.3,  1.0) : 58.0
    
        myFloor (57.3,  5.0) : 55.0
        myCeil  (57.3,  5.0) : 60.0
    
        myFloor (57.3, 10.0) : 50.0
        myCeil  (57.3, 10.0) : 60.0
    
    0 讨论(0)
  • 2020-11-27 16:30
    if (n % 5 == 1){
       n -= 1;
    } else if (n % 5 == 2) {
       n -= 2;
    } else if (n % 5 == 3) {
       n += 2;
    } else if (n % 5 == 4) {
       n += 1;
    }
    
    0 讨论(0)
提交回复
热议问题