In JavaScript, you can represent a number as type number (ex. 12), or as a type string (ex. '12').But both are not same. At times while coding we might have to convert the data from one type to other and there are many ways to do that. I would like to list few of the methods I know of data conversion from number to string.
1. Using .toString() method
There is a default string method that converts the data to string. The toString()
method returns the value of a String object.
myNumber = 100
myNumber.toString() // expected result: '100'
noNumber = NaN
noNumber.toString() // expected result: 'NaN'
decNum = 122.33
decNum.toString() // expected result: "122.33"
2. Using String()
The String()
method creates a primitive String type for the number that is passed to it.
myNumber = 99
String(myNumber) // expected result: '99'
fltNumber = 25.54
String(fltNumber) // expected result: '25.54'
3. Concatenating the Empty String
Adding empty string to the number value will convert the data to string is one of the simplest way to do the job. It is also considered to be faster than the above two when it comes to performance.
myNumber = 22
myString = '' + myNumber // expected result: '22'
fltNumber = 25.54
fltString = '' + fltNumber // expected result: '25.54'
4. Template Strings
With the introduction of template strings in ES6, injecting a number inside a String is a valid way of parsing an Integer or Float data type. This is the fastest way to convert the number to string.
myNumber = 22
flt = 50.205;
string = `${num}`; // expected result: '50'
floatString = `${flt}`; // expected result: '50.205'
5. Using toFixed() method
This is the least known method. But it can be little tricky with the decimal numbers.
myNumber = 22
myNumber.toFixed() // expected result: '22'
a = 56.9887
a.toFixed() // expected result: '57'
a.toFixed(4) // expected result: '56.9887'
Here is the comparison of the methods when it comes to the performance. Comment below if you know more ways.
Thank you
Top comments (0)