Convert a Number to a String in TypeScript

As a developer, I was recently required to convert a numeric value to its string representation. TypeScript provides several methods to achieve this. In this tutorial, I will explain how to convert a number to a string in TypeScript. We’ll explore them in detail with practical examples.

Convert a Number to a String in TypeScript

Now, let’s explore the different methods to convert a number to a string in TypeScript.

Method 1: Using the toString() Method

The best way to convert a number to a string in TypeScript is by using the built-in toString() method. This method is available on all number types in TypeScript. Here’s an example:

const age: number = 30;
const ageString: string = age.toString();
console.log(ageString); // Output: "30"

In this example, we have a variable age of type number with a value of 30. We call the toString() method on age and assign the result to a new variable ageString of type string. The toString() method converts the number to its string representation.

Here is the exact output in the screenshot below:

Convert a Number to a String in TypeScript

Check out Remove Spaces from a String in TypeScript

Method 2: Using Template Literals

Another convenient way to convert a number to a string is by using template literals. Template literals allow you to embed expressions inside string literals using the ${} syntax. Here’s an example and the TypeScript code:

const price: number = 9.99;
const priceString: string = `$${price}`;
console.log(priceString); // Output: "$9.99"

In this example, we have a variable price of type number with a value of 9.99. We use a template literal to create a string that includes the $ symbol followed by the price value. The price is automatically converted to a string inside the template literal.

Here is the exact output in the screenshot below:

Remove elements from list python

Check out Replace All Occurrences of a Substring in a String in TypeScript

Method 3: Using the String() Function

TypeScript also provides a global String() function that can be used to convert a number to a string. Here’s an example:

const distance: number = 42.195;
const distanceString: string = String(distance);
console.log(distanceString); // Output: "42.195"

In this example, we have a variable distance of type number with a value of 42.195, representing the length of a marathon in kilometers. We pass distance as an argument to the String() function, which converts it to a string and assigns the result to the distanceString variable.

Check out Check if a String is Empty in TypeScript

Method 4: Using Type Casting

TypeScript allows you to cast a number to a string using type casting explicitly. You can use the as keyword or angle brackets <> to perform the casting. Here’s an example:

const score: number = 100;
const scoreString1: string = score as string;
const scoreString2: string = <string>score;
console.log(scoreString1); // Output: "100"
console.log(scoreString2); // Output: "100"

In this example, we have a variable score of type number with a value of 100. We use two different type casting syntaxes to convert score to a string.

The first approach uses the as keyword, while the second approach uses angle brackets <>. Both approaches achieve the same result, and the choice between them is a matter of personal preference.

Read Check if a String is in an Enum in TypeScript

Convert a Number to a String in TypeScript – Real Example

Now, let me show you a real example and a complete code for converting a number to a string.

Suppose you are building a web application for a restaurant in New York City. You have a function that calculates the total bill amount based on the menu items ordered by a customer. Here’s how you can use number-to-string conversion in this context:

function calculateTotal(prices: number[]): string {
  const total = prices.reduce((sum, price) => sum + price, 0);
  const formattedTotal = total.toLocaleString('en-US', {
    style: 'currency',
    currency: 'USD',
  });
  return formattedTotal;
}

const menuPrices = [12.99, 8.5, 15.75, 6.25];
const billAmount = calculateTotal(menuPrices);
console.log(`Your total bill is ${billAmount}`);
// Output: "Your total bill is $43.49"

In this example, the calculateTotal function takes an array of menu item prices and calculates the total bill amount. We use the toLocaleString() method to convert the total to a string formatted as US currency. The resulting billAmount is then interpolated into a string using a template literal to generate the final output.

I executed the above TypeScript code, and you can see the exact output in the screenshot below:

Convert a Number to a String in TypeScript Real Example

Conclusion

In this tutorial, I have explained how to convert a number to a string in TypeScript using several methods, including the toString() method, template literals, the String() function, and type casting.

You may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.