How to round a number to a multiple of 8 in Node.js

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));
console.log(roundToMultipleOf(62, 8)); 
 
 
          
/*
run:
  
16
24
72
64
       
*/

 



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));
console.log(roundToMultipleOf(62, 8)); 
 
 
          
/*
run:
  
8
16
72
64
       
*/

 



answered Jun 8, 2024 by avibootz

Related questions

1 answer 109 views
2 answers 135 views
2 answers 149 views
1 answer 98 views
1 answer 118 views
1 answer 119 views
119 views asked Jun 8, 2022 by avibootz
1 answer 96 views
96 views asked Jun 8, 2022 by avibootz
...