# Rounding off numbers to some nearest power in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

#### JavaScript for beginners

Best Seller

74 Lectures 10 hours

#### Modern Javascript for Beginners + Javascript Projects

Most Popular

112 Lectures 15 hours

#### The Complete Full-Stack JavaScript Course!

Best Seller

96 Lectures 24 hours

We are required to write a JavaScript function that takes in a number and returns a number that can be represented as a power of 2 which is nearest to the input number.

For example: If the input number if 145.

Then the output should be 128 because 145 is the nearest such number to 128 which can be represented as 2^n for some whole number value of n.

## Example

The code for this will be −

const num = 145;
const nearestPowerOfTwo = num => {
// dealing only with non negative numbers
if(num < 0){
num *= -1;
}
let base = 1;
while(base < num){
if(num - base < Math.floor(base / 2)){
return base;
};
base *= 2;
};
return base;
};
console.log(nearestPowerOfTwo(num));

## Output

The output in the console −

128