Round number down to nearest power of 10 JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a number. The function should return a power of 10 which is nearest to the input number.

For example −

f(1) = 1
f(5) = 1
f(15) = 10
f(43) = 10
f(456) = 100
f(999) = 100

Example

const num = 2355;
const num1 = 346;
const num2 = 678;
const nearestPowerOfTen = (num) => {
   let count = 0;
   while(num > 1){
      count ++; num/= 10;
   };
   return Math.pow(10, count-1) * (Math.round(num) ? 10: 1);
}
console.log(nearestPowerOfTen(num));
console.log(nearestPowerOfTen(num1));
console.log(nearestPowerOfTen(num2));

Output

And the output in the console will be −

1000
100
1000
raja
Published on 25-Nov-2020 08:02:08
Advertisements