Convert int to string in javascript

Learn how to effectively convert int to string in javascript.

Using toString()

toString(base) function converts a given a number to the string. It takes an optional parameter base which can be used to specify the base in which the number will be represented as a string.

It works for floating point and exponential numbers also.

let num = 15;
num.toString(); //"15"
num.toString(2); //"1111" (binary)
num.toString(8); //"17"   (octa)
num.toString(16); //"f"   (hexa)

num = 15.55;
num.toString(); //"15.55"

num = 15e10;
num.toString(); //"150000000000"


By concatenating with empty string ""

This the most simplest method which can be used to convert a int to string in javascript.

As javascript is loosely typed language when we concatenate a number with string it converts the number to string.

15 + '' = "15";
15.55 + '' = "15.55";
15e10 + '' = "150000000000"

As you can see we can also convert floating point and exponential numbers.


Using Template Strings to convert int to string

We can also use ES6 Template Strings to convert a number to string.

let num = 15;
console.log(`"${num}"`);   // "15"

let floatingNum = 15.55;
console.log(`"${floatingNum}"`); // "15.55"

let expNum = 15e10;
console.log(`"${expNum}"`); // "150000000000"

Leave a Reply

Your email address will not be published. Required fields are marked *