Returning the expanded form of a number in JavaScript

JavascriptWeb DevelopmentFront End Technology

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 −

 Live Demo

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
raja
Published on 17-Apr-2021 11:31:16
Advertisements