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

2 Answers

0 votes
function roundToMultipleOf(num: number, roundTo: number) {
    return (num + (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(num: number, multipleOf: number) {
    return multipleOf * Math.round(num / 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 137 views
2 answers 122 views
1 answer 130 views
2 answers 165 views
2 answers 119 views
2 answers 124 views
2 answers 105 views
...