Hi guys, I have recreated toString method of number type in javascript to have some understanding about the method. I wanted to share it with you guys.

Generally, toString(base) method will convert a given number to the base specified as argument, for example:

let num = 255;

console.log(num.toString(16)) => 'ff'

console.log(num.toString(2)) => '11111111'

console.log(num.toString(8)) => '377'

As you can see toString method will convert a number to the specified base.

255 got converted to 'ff' -> 'ff' is 255 in base-16(Hexdecimal number), '11111111' is 255 in base-2(Binary number), '377' is 255 in base-8(Octal Number).

You can pass a base number between 2-36 to toString method, and the method will convert the number to the provided base and return the result as a string.

I have created a function toString which will exactly do the same, pass the number and base to the function, it will convert the number to the supplied base and return the result as a string. Here is the toString function,

```
function toString(num, base) {
let arr = []; //array for holding the remainder
const baseArr = [
0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 ,
8 , 9 , 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z'
]; //baseArray for conversion
while (num >= base) {
remainder = num % base;
num = num / base;
num = Math.trunc(num);
arr.unshift(remainder);
}
arr.unshift(num);
let result = [];
for (let i=0; i<arr.length; i++) {
result.push(baseArr[arr[i]]);
}
return result.join('');
}
console.log(toString(255, 8)); // Output: '377'
console.log(toString(255, 16)); // Output: 'ff'
console.log(toString(255, 2)); // Output: '11111111'
```

Here, I have a baseArr to represent base number system, if we pass 16 as base to toString method, the array 0 to 15 will be picked for conversion, for base-36 the whole array will be taken for conversion.

Then, I am performing division on the number and getting the remainder from the number, if the remainder is 10, then it will be converted to string 'a' using the baseArr.

We can create a similar function like this for encryption. I will say 'ff' to you, if you're from programming world, you will understand 'ff' means the number 255 in base-16 system. Encryption works like that.

I hope this post will give you some idea about the method toString and its uses. Thank you

## Top comments (0)