Open In App

How to Convert Number to String in TypeScript ?

Last Updated : 07 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Converting floats to strings is a common operation in programming that enables us to work with numeric data in a more flexible and controlled manner.

Below are the approaches:

Convert Number to String Using toString() Method

In this approach, we are using toString() method. That is used to convert a value to a string. we will pass the numeric value and it will convert that value into a string.

Syntax:

Object.toString()

Example: In the below code we are passing the number value to the toString() method which converts the float to a string.

Javascript




let numberValue: number = 7.577474;
let stringValue: string = numberValue.toString();
console.log(stringValue);
console.log(typeof stringValue);


Output:

7.577474
string

Convert Number to String Using Template Literals

Template literals are a feature in JavaScript (and TypeScript) that allows us to create multi-line strings and embed expressions within them.

Syntax:

let varName: string = `${object}`;

Example: The number variable myFloat is interpolated into the template literal ${myFloat}, which converts it to a string. The resulting string is then assigned to the variable myString.

Javascript




let myFloat: number = 3.14159;
let myString: string = `${myFloat}`;
console.log(myString);
console.log(typeof myString);


Output:

3.14159
string

Convert Number to String Using toFixed() Method

The toFixed() method is used to round a number to two decimal places and return the result as a string.

Syntax:

let roundedNumber = number.toFixed(digits);

Example: Below is the practical implementation of the above method.

Javascript




let num: number = 10.555;
let roundedNum: string = num.toFixed(2);
console.log(roundedNum);
console.log(typeof roundedNum);


Output:

10.55
string

Convert Number to String Using String Constructor

The String constructor can be used to create a new string object. It can also be used to convert a value to a string. in this approach we will see how we can convert float value to string using String Constructor.

Syntax:

let str: string = String(floatValue);

Example: In this example, String(num) converts the number 123.78 into a string “123.78” using the String constructor.

Javascript




let num: number = 123.78;
let str: string = String(num);
 
console.log(str);
console.log(typeof str);


Output:

123.78
string


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads