How to round a number to a multiple of 8 in Java

2 Answers

0 votes
public class Program {
    private static int roundToMultipleOf(int number, int roundTo) {
    	return (number + (roundTo - 1)) & ~(roundTo - 1);
    }
    
    public static void main(String args[]) {
        System.out.println(roundToMultipleOf(9, 8));
        System.out.println(roundToMultipleOf(19, 8));
        System.out.println(roundToMultipleOf(71, 8));
    }
}

   
   
/*
run:
   
16
24
72
   
*/

 

 



answered Jun 8, 2024 by avibootz
0 votes
import java.lang.Math;

public class Program {
    public static double roundToMultipleOf(double number, double multipleOf) {
        return multipleOf * Math.round(number / multipleOf);
    }

    public static void main(String[] args) {
        System.out.println(roundToMultipleOf(9, 8));
        System.out.println(roundToMultipleOf(19, 8));
        System.out.println(roundToMultipleOf(71, 8));
    }
}


   
   
/*
run:
   
8.0
16.0
72.0
   
*/

 

 



answered Jun 8, 2024 by avibootz

Related questions

2 answers 129 views
2 answers 137 views
2 answers 122 views
1 answer 130 views
2 answers 165 views
2 answers 119 views
2 answers 124 views
...