How To Convert A Number To A String In TypeScript?

Convert a Number to a String in TypeScript

This tutorial will show you some of the most common ways to convert a number to a string in TypeScript. This is a necessary skill that every TypeScript developer should have, so please stay tuned and follow us.

Convert a number to a string in TypeScript

Often you will have a number and want to convert it to a string to use JavaScript’s string methods. For example, when we want to count how many digits in an integer, we can convert it into a string and then use the string.length method. So, here are the two common ways to achieve this.

Using String()

JavaScript has supported many methods to work with strings, and one of the most familiar ones is the string() method. The string() method will convert any value into string. 

Syntax: 

String(value) 

Parameters: 

  • value: the value that you want to convert into string.

Example: 

var myBool = true;
var myString = String(myBool);
console.log(myString);
console.log(typeof myString);

Output

true
string

Now, let’s apply it to solve our problem. If we want to convert a number value into string, put the value inside the string method. 

Completed code: 

var myNum = 1286;
var result = "";
result = String(myNum);
console.log("This is a string:", result);

Output

This is a string: 1286

Using ToString()

One other way to do this is using the toString() method. The toString() method will return the value of an object in string format. 

Syntax:

value.toString()

Parameters: 

  • value: The value that you want to convert into string.

Example: 

var myBool = true;
var myStr = myBool.toString();
console.log(myStr);
console.log(typeof myStr);

Output: 

true
string

Now let’s apply it to convert a number to a string: 

var myNum = 1286;
var result = "";
result = myNum.toString();
console.log("This is a string:", result);
console.log(typeof result);

Output: 

This is a string: 1286
string

Now we can apply those to the problem I have stated above: count the digits of an integer. The idea is to use the string.length method.

Completed code: 

var myNum = 1286;
var str = myNum.toString();
var result = str.length;
console.log(result);

Output: 

4

Summary

This tutorial covers several methods to convert a number to a string in TypeScript. The idea is to use the String() and toString() methods. Let’s try them to get your desired results. Thank you for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *