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
Returning the expanded form of a number in JavaScript
The expanded form of a number breaks down each digit into its place value. For example, 1234 becomes "1000 + 200 + 30 + 4". This is useful for teaching place value concepts and number decomposition.
Problem
We need to write a JavaScript function that takes a number and returns a string showing the expanded form, indicating the place value of each non-zero digit.
Example
const num = 56577;
const expandedForm = (num = 0) => {
const str = String(num);
let res = '';
let multiplier = Math.pow(10, str.length - 1);
for(let i = 0; i
50000 + 6000 + 500 + 70 + 7
10000 + 2000 + 40 + 5
7
How It Works
The function converts the number to a string to access individual digits. It calculates a multiplier starting from the highest place value (10^(length-1)). For each digit, if it's non-zero, it multiplies by the current place value and adds to the result. The multiplier decreases by 10 each iteration.
Alternative Approach Using Filter
const expandedFormFilter = (num) => {
return String(num)
.split('')
.map((digit, index, arr) => {
const placeValue = Math.pow(10, arr.length - 1 - index);
return +digit * placeValue;
})
.filter(value => value > 0)
.join(' + ');
};
console.log(expandedFormFilter(56577));
console.log(expandedFormFilter(12045));
50000 + 6000 + 500 + 70 + 7
10000 + 2000 + 40 + 5
Key Points
- Convert number to string to access individual digits
- Calculate place values using powers of 10
- Skip zero digits to avoid "0" terms in the output
- Join non-zero terms with " + " separator
Conclusion
Both approaches effectively break down numbers into their place value components. The first method uses a loop with manual string building, while the second leverages array methods for a more functional approach.
