Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 15, 2020 10:41 am GMT

5 ways to convert number to string in JavaScript

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 = 100myNumber.toString() // expected result: '100'noNumber = NaNnoNumber.toString() // expected result: 'NaN'decNum = 122.33decNum.toString() // expected result: "122.33"
Enter fullscreen mode Exit fullscreen mode

2. UsingString()

The String() method creates a primitive String type for the number that is passed to it.

myNumber = 99String(myNumber) // expected result: '99'fltNumber = 25.54String(fltNumber) // expected result: '25.54'
Enter fullscreen mode Exit fullscreen mode

3. Concatenating the EmptyString

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 = 22myString = '' + myNumber // expected result: '22'fltNumber = 25.54fltString = '' + fltNumber // expected result: '25.54'
Enter fullscreen mode Exit fullscreen mode

4. TemplateStrings

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 = 22flt = 50.205;string = `${num}`;      // expected result: '50' floatString = `${flt}`; // expected result: '50.205'
Enter fullscreen mode Exit fullscreen mode

5. Using toFixed() method

This is the least known method. But it can be little tricky with the decimal numbers.

myNumber = 22myNumber.toFixed() // expected result: '22'a = 56.9887a.toFixed() // expected result: '57'a.toFixed(4) // expected result: '56.9887'
Enter fullscreen mode Exit fullscreen mode

Here is the comparison of the methods when it comes to the performance. Comment below if you know more ways.
Thank you


Original Link: https://dev.to/sanchithasr/5-ways-to-convert-number-to-string-3fhd

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To