Converting number of corresponding string without using library function in JavaScript

Converting a number to a string without using built-in functions like String() or toString() requires extracting individual digits and building the result character by character.

Problem

We need to write a JavaScript function that takes a number and converts it to its corresponding string representation without using the built-in functions String() or toString() or direct string concatenation.

Approach

The solution extracts digits from right to left using the modulo operator (%) and integer division. Each digit is converted to its character representation and prepended to build the final string.

Example

const num = 235456;

const convertToString = (num) => {
    let res = '';
    while(num) {
        res = (num % 10) + res;
        num = Math.floor(num / 10);
    }
    return res;
};

console.log(convertToString(num));
console.log(typeof convertToString(num));
235456
string

How It Works

The algorithm works by:

  1. Extract rightmost digit: num % 10 gets the last digit
  2. Prepend to result: Add the digit to the front of our result string
  3. Remove processed digit: Math.floor(num / 10) removes the last digit
  4. Repeat: Continue until no digits remain

Handling Edge Cases

const convertToString = (num) => {
    if (num === 0) return '0';
    
    let res = '';
    let isNegative = num < 0;
    num = Math.abs(num);
    
    while(num) {
        res = (num % 10) + res;
        num = Math.floor(num / 10);
    }
    
    return isNegative ? '-' + res : res;
};

console.log(convertToString(0));      // "0"
console.log(convertToString(-123));   // "-123"
console.log(convertToString(456));    // "456"
0
-123
456

Conclusion

This approach successfully converts numbers to strings by extracting digits mathematically and building the result character by character. The enhanced version handles zero and negative numbers correctly.

Updated on: 2026-03-15T23:19:00+05:30

394 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements