Using Number.toString() in TypeScript

avatar

Borislav Hadzhiev

Last updated: Mar 8, 2022

banner

Photo from Unsplash

Using Number.toString() in TypeScript #

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.

index.ts
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.

index.ts
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.

index.ts
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.

index.ts
// ⛔️ 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 parentheses before calling the toString() method.

index.ts
const str = (7).toString();

Perhaps a better approach in this situation is to use the String() function.

index.ts
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.

The 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.

index.ts
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 it is more widely used in the codebases I've worked on.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.