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
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:
-
Extract rightmost digit:
num % 10gets the last digit - Prepend to result: Add the digit to the front of our result string
-
Remove processed digit:
Math.floor(num / 10)removes the last digit - 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.
