Given a number, the task is to convert the given number to a string in JavaScript. It is useful for formatting numbers, concatenating with other strings, or displaying data. There are several methods to convert number to string in JavaScript.
Approach 1: Using toString() Method
The most common and straightforward way to convert a number to a string in JavaScript is by using the toString()
method.
const num = 123; const str = num.toString(); console.log(str); // Output: "123"
- Explanation: The
toString()
method converts the number to its string representation.
Approach 2: Using String() Constructor
Another simple approach is to use the String()
constructor, which can convert any data type to a string.
const num = 123; const str = String(num); console.log(str); // Output: "123"
- Explanation: The
String()
constructor converts the number to a string.
Approach 3: Using Template Literals
Template literals can also be used to convert a number to a string by interpolating it within a template string.
const num = 123; const str = `${num}`; console.log(str); // Output: "123"
- Explanation: The number
num
is interpolated within the template string, automatically converting it to a string.
Approach 4: Using toFixed() Method
If you need to format a number with a specific number of decimal places, the toFixed()
method can be used.
const num = 123.456; const str = num.toFixed(2); console.log(str); // Output: "123.46"
- Explanation: The
toFixed(2)
method formats the number with two decimal places and returns it as a string.
Approach 5: Using Concatenation
Simple concatenation with an empty string is another way to convert a number to a string.
const num = 123; const str = num + ''; console.log(str); // Output: "123"
- Explanation: Concatenating the number with an empty string coerces it into a string.
Approach 6: Using toLocaleString() Method
The toLocaleString()
method provides a way to format numbers based on the locale settings of the user’s environment.
const num = 1234567.89; const str = num.toLocaleString(); console.log(str); // Output: "1,234,567.89" (formatted based on locale)
- Explanation: The
toLocaleString()
method formats the number according to the locale settings.