Round number down to nearest power of 10 JavaScript


In the provided problem statement, our task is to write the function for partial sum in an array of arrays with the help of Javascript. So here we will be given a variety of arrays and we need to compute the sum of each row and show the result.

Understanding the problem statement

The problem statement is asking for creating a function in Javascript which rounds down a given input number to the nearest power of 10. For example if there is an input 1365 so the output should be 1000. That is the nearest power of 10 which is less than or equal to 1365. Just like that if the input is 987 so the output will be 1000.

Logic for the above problem

In the solution we will calculate the exponent of the highest power of 10 which is less than or equal to the absolute value of the input number. After that we will calculate the actual power of 10 with the help of Math.pow function. The input number will be divided by the power of 10 and rounded down with the Math.floor function and then multiplied by the power of 10 to get the rounded down result.

Algorithm

Step 1 − Create a function to round down to power of 10. And pass an argument as a number.

Step 2 − Check the condition that the provided number is equal to zero. If this statement is true then return zero.

Step 3 − Otherwise calculate the exponent of the highest power of 10 which is less than or can be equal to the absolute value of the input number with the help of Math.log10 method and the Math.floor function.

Step 4 − Then calculate the actual power of 10 with the help of Math.pow function.

Step 5 − Divide the given input number with the power of 10 and round down the result with Math.floor function.

Step 6 − Multiply with the power of 10 to get the rounded result.

Code for the algorithm

//function to round down to power of 10
function roundToPowerOf10(number) {
   if (number === 0) {
      return 0;
   } else {
      let exponent = Math.floor(Math.log10(Math.abs(number)));
      let powerOf10 = Math.pow(10, exponent);
      return Math.floor(number / powerOf10) * powerOf10;
   }
}

const number = 1356;
const theNumber = roundToPowerOf10(number);
console.log(theNumber); 

Complexity

The code uses constant time operations like Math.log10 and Math.pow. So the time complexity of the code is O(1) or we can say constant time. The space complexity for the algorithm is also O(1) because we are using a constant amount of memory to store variables.

Conclusion

The function shown here can be used to round down the given number to the nearest power of 10 in Javascript with a constant time and space complexity.

Updated on: 18-May-2023

591 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements