- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Returning the expanded form of a number in JavaScript
Problem
We are required to write a JavaScript function that takes in a number and returns a string of the expanded form of the number, indicating the place value of each number.
Example
Following is the code −
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 < str.length; i++){ const el = +str[i]; const next = +str[i + 1]; if(el){ res += (el * multiplier); }; if(next){ res += ' + '; }; multiplier /= 10; }; return res; }; console.log(expandedForm(num));
Output
Following is the console output −
50000 + 6000 + 500 + 70 + 7
Advertisements