Last updated: Feb 28, 2024
Reading timeยท2 min
Use the String()
constructor to convert a number to a string in
TypeScript.
The String()
constructor converts the supplied value to a string and returns
the result.
const num = 100; // ๐๏ธ const str: string const str = String(num); console.log(str); // ๐๏ธ "100" console.log(typeof str); // ๐๏ธ "string"
We used the String() constructor to convert a number to a string in TypeScript.
The only parameter the function takes is the value that will be converted to a string.
If you convert a negative number to a string, the sign is preserved.
const num = -100; const str = String(num); console.log(str); // ๐๏ธ "-100" console.log(typeof str); // ๐๏ธ "string"
If you pass a number with a decimal to the String()
constructor, the decimal
is preserved.
const num = 14.5; const str = String(num); console.log(str); // ๐๏ธ "14.5"
toString()
methodYou can also use the Number.toString method to convert a number to a string in TypeScript.
const num = 100; const str = num.toString(); console.log(str); // ๐๏ธ "100" console.log(typeof str); // ๐๏ธ "string"
The Number.toString()
method returns a string representing the specified
number.
However, note that you can't directly call a method on a number.
// โ๏ธ Error const str = 100.toString();
The example shows how trying to call a built-in method on a number throws an error.
You can wrap the number in parentheses before calling the toString()
built-in
method.
const str = (100).toString(); console.log(str); // ๐๏ธ "100" console.log(typeof str); // ๐๏ธ "string"
When using the Number.toString()
method, the sign is also preserved after the
conversion.
const str = (-100).toString(); console.log(str); // ๐๏ธ "-100" console.log(typeof str); // ๐๏ธ "string"
Which approach you pick is a matter of personal preference. I prefer using the
String()
constructor as it is more widely used in the codebases I've worked
on.
If you need to convert a string to a number, check out the following article.
You can learn more about the related topics by checking out the following tutorials: