JavaScript provides several ways to convert an integer or floating-point number into a string. The most common approaches include toString(), String(), string concatenation, and toLocaleString().
- Use toString() for a simple and direct conversion.
- Use String() when you want an explicit and general-purpose conversion.
- Use toLocaleString() when the number needs to be formatted according to a locale.
Approach 1: Using toString() Method
The toString() method converts a number into its string representation. It can also accept an optional radix parameter to convert the number into a different base.
Example: In this example, we use toString() to convert numbers into strings and convert 7 into its binary representation.
let a = 20;
console.log(a.toString());
console.log((50).toString());
console.log((7).toString(2)); // 7 in base 2 (binary)
Output
20 50 111
Approach 2: Using the String() Constructor
The String() function explicitly converts a number into a string. Unlike toString(), it does not accept a radix argument for base conversion.
Example: In this example, we use String() to convert both an integer and a floating-point number into strings.
console.log(String(52));
console.log(String(35.64));
Output
52 35.64
Note: String() performs type conversion but does not provide the base-conversion feature available with Number.prototype.toString().
Approach 3: Using Empty String Concatenation
Adding an empty string to a number implicitly converts the number into a string. This is a short and simple approach, although it is less explicit than String() or toString().
Example: In this example, concatenating an empty string with 50 converts the number into a string.
let a = '' + 50;
console.log(a);
console.log(typeof a);
Output
50 string
Approach 4: Using toLocaleString() Method
The toLocaleString() method converts a number into a string while formatting it according to the specified locale. It is particularly useful when displaying numbers with locale-specific separators and formatting.
Example: In this example, we use toLocaleString() to convert a number into a string.
let n = 92;
let s = n.toLocaleString();
console.log(s);
console.log(typeof s);
Output
92 string
For larger numbers, locale-specific formatting becomes more noticeable:
let n = 1234567;
console.log(n.toLocaleString('en-US'));
Output
1,234,567
Approach 5: Using Lodash _.toString() Method
Lodash provides the _.toString() method to convert a value into a string. Unlike the native String() function, it preserves the sign of negative zero.
Example: In this example, we use Lodash _.toString() to convert -0 into a string.
const _ = require("lodash");
console.log(_.toString(-0));
Output:
-0