Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Round number down to nearest power of 10 JavaScript
In JavaScript, rounding down a number to the nearest power of 10 involves finding the highest power of 10 that is less than or equal to the given number. For example, 1365 rounds down to 1000, and 987 rounds down to 100.
Understanding the Problem
The task is to create a function that rounds down any given number to the nearest power of 10. Powers of 10 are numbers like 1, 10, 100, 1000, etc. For a number like 1365, the nearest lower power of 10 is 1000, while for 87, it would be 10.
Algorithm
Step 1: Handle the special case where the input is 0
Step 2: Calculate the exponent using Math.log10() and Math.floor()
Step 3: Find the actual power of 10 using Math.pow()
Step 4: Divide the number by this power of 10, floor it, then multiply back
Implementation
function roundToPowerOf10(number) {
// Handle zero case
if (number === 0) {
return 0;
}
// Calculate the exponent of the highest power of 10
let exponent = Math.floor(Math.log10(Math.abs(number)));
let powerOf10 = Math.pow(10, exponent);
// Round down and multiply back
return Math.floor(number / powerOf10) * powerOf10;
}
// Test with different numbers
console.log(roundToPowerOf10(1365)); // 1000
console.log(roundToPowerOf10(987)); // 100
console.log(roundToPowerOf10(45)); // 10
console.log(roundToPowerOf10(8)); // 1
console.log(roundToPowerOf10(-234)); // -200
1000 100 10 1 -200
How It Works
The function uses Math.log10() to find the logarithm base 10 of the absolute value. Math.floor() gives us the integer part, which represents the exponent of the highest power of 10. For example:
console.log(Math.log10(1365)); // 3.135... console.log(Math.floor(3.135)); // 3 console.log(Math.pow(10, 3)); // 1000
3.1354064987748903 3 1000
Edge Cases
// Testing edge cases console.log(roundToPowerOf10(0)); // 0 console.log(roundToPowerOf10(10)); // 10 (exact power of 10) console.log(roundToPowerOf10(100)); // 100 console.log(roundToPowerOf10(-50)); // -50
0 10 100 -50
Complexity Analysis
Time Complexity: O(1) - All mathematical operations are constant time
Space Complexity: O(1) - Uses only a few variables regardless of input size
Conclusion
This function efficiently rounds down numbers to the nearest power of 10 using logarithmic calculations. It handles both positive and negative numbers with constant time and space complexity.
