Borislav Hadzhiev
Tue Mar 08 2022·2 min read
Photo by Nicolas Tissot
Use the String()
object to convert a number to a string in TypeScript, e.g.
const str = String(num)
. When used as a function, the String
object converts
the passed in value to a primitive string and returns the result.
const num = 100; // ✅ Convert Number to String // 👇️ const str: string const str = String(num); console.log(str); // 👉️ "100" console.log(typeof str); // 👉️ "string" // ✅ Convert String to Number const backToNumber = Number(str); console.log(backToNumber); // 👉️ 100
We used the String function 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()
function, the decimal is
preserved.
const num = 14.5; const str = String(num); console.log(str); // 👉️ "14.5"
You might also see the Number.toString method used to achieve the same result.
const num = 100; const str = num.toString(); console.log(str); // 👉️ "100" console.log(typeof str); // 👉️ "string"
The Number.toString()
method also converts a number to a string.
However, note that you can't directly call a method on a number.
// ⛔️ Error: An identifier or keyword // cannot immediately follow a numeric literal. const str = 100.toString();
The example shows how trying to call a built-in method on a number throws an error.
If you are in that situation, wrap the number in parenthesis before calling the 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()
function as I it more widely used in the codebases I've worked on.