DEV Community

Nitin Sijwali
Nitin Sijwali

Posted on • Updated on

Convert number to string in JS

Looking at the title, you might think it's a simple task that any noob can complete. right??
However, the actual question was, write a function that accepts an args as a number and returns the string version of the same number, given that you cannot use string methods like function toString(), or initialise a variable with an empty string, or use any other tricks.

So we will approach this problem by keeping two points in mind

  • Every number is formed from digits 0-9;
  • Divide and conquer rule
  • Recursion
let stringNum;
const arr = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
let temp;
function convertToString(num) {
  if (num > 0) { // condition will give the string but in reverse order.
    const dividend = num % 10;
    if (temp) {
      temp += arr[dividend];
    } else {
      temp = arr[dividend];
    }
    convertToString(Math.floor(num / 10)); // recursion
  } else {
// here we will reverse the string to get the actual number in string format.
    for (let i = temp.length - 1; i >= 0; i--) {
      if (stringNum) {
        stringNum += temp.charAt(i);
      } else {
        stringNum = temp.charAt(i);
      }
    }

  }
  return stringNum;
}

const result = convertToString(125)
console.log(result) // "125"
Enter fullscreen mode Exit fullscreen mode

Please give it a shot and let me know what you think.

Please ❤️ it and share it your with friends or colleagues. Spread the knowledge.


Thats all for now. Keep learning and have faith in Javascript❤️

Top comments (2)

Collapse
 
rollergui profile image
Guilherme

man, that's insane hahahaha but it was very creative... congrats!

Collapse
 
nsijwali profile image
Nitin Sijwali

Thanks 😊