How to round a number to the next power of 2 in JavaScript

1 Answer

0 votes
/**
 * Rounds an integer up to the next power of 2.
 *
 * returns the next power of 2 greater than or equal to n
 */
function roundToNextPowerOf2(n) {
  if (n <= 0) return 1;
  return Math.pow(2, Math.ceil(Math.log2(n)));
}

const num = 21;
console.log(`Next power of 2: ${roundToNextPowerOf2(num)}`);




/*
run:
 
Next power of 2: 32
 
*/

 



answered Oct 29, 2025 by avibootz
...