Borislav Hadzhiev
Tue Mar 08 2022·2 min read
Photo by Jad Limcaco
Use the Number.toString()
method to convert a number to a string in
TypeScript, e.g. const str = num.toString()
. The Number.toString()
method
returns a string that represents the specified number. When used on negative
numbers, the sign is preserved after the conversion.
const num = 701; // ✅ Use Number.toString() const str = num.toString(); console.log(str); // 👉️ "701" console.log(typeof str); // 👉️ "string" // ✅ Alternatively, use String() const strAgain = String(num); console.log(strAgain); // 👉️ "701" console.log(typeof strAgain); // 👉️ "string"
We used the Number.toString method to convert a number to a string in TypeScript.
The method returns a string that represents the given number.
If you call the Number.toString()
method on a negative number, the sign is
preserved.
const num = -51; const str = num.toString(); console.log(str); // 👉️ "-51"
If the Number.toString()
method is called on a number with a decimal, the
decimal is preserved.
const num = 14.54; const str = num.toString(); console.log(str); // 👉️ "14.54" console.log(typeof str); // 👉️ "string"
The dot sign in the string is used to separate the decimal places.
Note that you can't directly call the Number.toString()
method on a number.
// ⛔️ Error: An identifier or keyword cannot // immediately follow a numeric literal.ts(1351) const str = 7.toString();
The example shows how trying to call the built-in method on a number literal throws an error.
To get around this, we have to wrap the number literal in parenthesis before
calling the toString()
method.
const str = (7).toString();
Perhaps a better approach in this situation is to use the String()
function.
const str = String(7); console.log(str); // 👉️ "7" console.log(typeof str); // 👉️ "string"
The String
function also converts a number to a string, but solves this issue
seamlessly, because we aren't calling any built-in methods on the number
literal.
String()
function can be used as a replacement for the Number.toString()
method.It also preserves the negative sign and the decimal part when converting numbers to strings.
const str = String(-7); console.log(str); // 👉️ "-7" const str2 = String(7.432); console.log(str2); // 👉️ 7.432
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.