How to round a number to the previous power of 2 in TypeScript

1 Answer

0 votes
/**
 * Rounds an integer down to the previous power of 2.
 *
 * return the previous power of 2 less than or equal to n
 */
function roundToPreviousPowerOf2(n: number): number {
  return n > 0 ? 2 ** Math.floor(Math.log2(n)) : 0;
}

const num: number = 21;

console.log(`Previous power of 2: ${roundToPreviousPowerOf2(num)}`);




/*
run:
 
"Previous power of 2: 16" 

*/

 



answered Oct 30, 2025 by avibootz
...