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

2 Answers

0 votes
function roundToMultipleOf(number, roundTo) {
    return (number + (roundTo - 1)) & ~(roundTo - 1);
}

console.log(roundToMultipleOf(9, 8));
console.log(roundToMultipleOf(19, 8));
console.log(roundToMultipleOf(71, 8));



         
/*
run:
 
16
24
72
      
*/

 



answered Jun 8, 2024 by avibootz
0 votes
function roundToMultipleOf(number, multipleOf) {
    return multipleOf * Math.round(number / multipleOf);
}

console.log(roundToMultipleOf(9, 8));
console.log(roundToMultipleOf(19, 8));
console.log(roundToMultipleOf(71, 8));



         
/*
run:
 
8
16
72
      
*/

 



answered Jun 8, 2024 by avibootz

Related questions

2 answers 133 views
2 answers 139 views
1 answer 133 views
2 answers 169 views
2 answers 122 views
2 answers 125 views
2 answers 107 views
...