Convert String to Number in TypeScript [With Examples]

As a TypeScript developer, you will face scenarios of converting strings to numbers for data manipulation, calculations, and integrations. There are various methods to do this. Let me explain. In this tutorial, I will explain how to convert a string to a number in TypeScript using different approaches with examples.

When building TypeScript applications, we often receive data from user inputs, API responses, or configuration files in string format. However, we need these values as proper number types to perform mathematical operations or comparisons. TypeScript’s static typing system helps ensure type safety, but we still need reliable conversion methods.

So, now, let me show you some useful methods ot converting strings to numbers in TypeScript.

TypeScript String to Number Conversion Methods

In TypeScript, you can use various methods to convert strings to numbers. Here are the methods with examples.

1. Using the Unary Plus (+) Operator

The unary plus operator in TypeScript is arguably the easiest way to convert a string into a number. Here is how to do this.

// Converting string to number using unary plus
const strValue: string = "42";
const numValue: number = +strValue; // 42

console.log("String Value:", strValue);
console.log("Converted Number Value:", numValue);

This code takes a string ("42") and converts it into a number using the unary plus operator (+). The console.log statements help verify the conversion.

Here is the exact output in the screenshot below:

typescript string to number

This method works well for simple conversions but has limitations when dealing with non-numeric strings or special formats.

Check out Convert String to Enum in Typescript

2. Using the Number() Constructor

The Number() constructor provides another straightforward approach to convert strings to numbers in TypeScript.

Here is the complete code:

// Using Number() constructor
const strValue: string = "123.45";
const numValue: number = Number(strValue); // 123.45

console.log("String Value:", strValue);
console.log("Converted Number Value:", numValue);

This code declares a string variable strValue with the value "123.45", then converts it to a number using the Number() constructor. Finally, it logs both the original string and the converted number to the console.

I executed the above code using VS code and you can see the output in the screenshot below:

string to number typescript

The Number() constructor handles both integers and floating-point numbers, making it versatile for various conversion needs.

Read Convert String to Date in TypeScript

3. Using parseInt() for Integer Conversion

When you specifically need an integer result, parseInt() is the recommended method in TypeScript to convert a string to an integer.

// Converting to integer with parseInt()
const strValue: string = "42.75";
const intValue: number = parseInt(strValue, 10); // 42

console.log("String Value:", strValue);
console.log("Converted Integer Value:", intValue);

This code declares a string variable strValue with the value "42.75", then uses parseInt() with a radix of 10 to convert it to the integer 42. Finally, it logs both the original string and the converted integer to the console.

You can see the exact output in the screenshot below:

typescript convert string to number

Note the second parameter (10) in the parseInt() function. This specifies the radix or base of the numeral system (decimal in this case). Always include this parameter to avoid potential issues with string values that start with ‘0’.

Read Convert Date to UTC in Typescript

4. Using parseFloat() for Decimal Numbers

For decimal or floating-point numbers in TypeScript, parseFloat() is the appropriate choice:

// Converting to float with parseFloat()
const strValue: string = "42.75";
const floatValue: number = parseFloat(strValue); // 42.75

console.log("String Value:", strValue);
console.log("Converted Float Value:", floatValue);

This code declares a string variable strValue with the value "42.75", then converts it to a floating-point number using parseFloat(). Finally, it logs both the original string and the converted float to the console.

Unlike parseInt(), parseFloat() doesn’t require a radix parameter and always interprets the input in base 10.

Compare the Conversion Methods

Here is the comparison table you can follow to find out which method suits your requirements.

MethodHandles DecimalsReturns NaN for Invalid InputHandles Leading/Trailing SpacesNotes
Unary Plus (+)YesYesNoMost concise syntax
Number()YesYesYesConverts empty strings to 0
parseInt()No (truncates)YesYesRequires radix parameter
parseFloat()YesYesYesStops at invalid characters

Read Convert Date to String Format dd/mm/yyyy in Typescript

Handle Edge Cases in String to Number Conversion

Converting strings to numbers isn’t always straightforward. Let’s examine how to handle common edge cases:

Working with Non-Numeric Strings

When converting strings that aren’t valid numbers, all methods will return NaN (Not a Number):

const nonNumeric: string = "Hello";
console.log(+nonNumeric); // NaN
console.log(Number(nonNumeric)); // NaN
console.log(parseInt(nonNumeric, 10)); // NaN
console.log(parseFloat(nonNumeric)); // NaN

Validating Numeric Strings Before Conversion

It’s often wise to validate strings before attempting conversion:

function isNumeric(value: string): boolean {
  return !isNaN(parseFloat(value)) && isFinite(Number(value));
}

function safelyConvertToNumber(value: string): number | null {
  return isNumeric(value) ? Number(value) : null;
}

// Usage
const validInput = "42.5";
const invalidInput = "42px";

console.log(safelyConvertToNumber(validInput)); // 42.5
console.log(safelyConvertToNumber(invalidInput)); // null

Handling Different Number Formats

When dealing with currency or formatted numbers like “$1,234.56”, you’ll need to clean the string first:

function convertCurrencyToNumber(value: string): number {
  // Remove currency symbols, commas, and other non-numeric characters (except decimal point)
  const cleanedValue = value.replace(/[^0-9.-]+/g, "");
  return Number(cleanedValue);
}

// Usage
console.log(convertCurrencyToNumber("$1,234.56")); // 1234.56

Check out Convert Typescript Dictionary to String

TypeScript String to Number Conversion Examples

Let’s explore some practical applications of string to number conversion in TypeScript projects:

1. Form Input Processing

When building forms for applications, user inputs often come as strings that need conversion:

// User registration form example
interface UserFormData {
  name: string;
  age: string; // From input field
  income: string; // From input field
}

interface ProcessedUserData {
  name: string;
  age: number;
  income: number;
}

function processFormData(data: UserFormData): ProcessedUserData {
  return {
    name: data.name,
    age: Number(data.age) || 0, // Default to 0 if invalid
    income: Number(data.income) || 0
  };
}

2. API Response Handling

APIs sometimes return numeric values as strings that need conversion for further processing:

interface ProductResponse {
  id: string;
  name: string;
  price: string;
  stockQuantity: string;
}

interface ProcessedProduct {
  id: number;
  name: string;
  price: number;
  stockQuantity: number;
}

function processProductData(data: ProductResponse): ProcessedProduct {
  return {
    id: parseInt(data.id, 10),
    name: data.name,
    price: parseFloat(data.price),
    stockQuantity: parseInt(data.stockQuantity, 10)
  };
}

3. Configuration Processing

When reading configuration values from environment variables or files:

// Environment variables are always strings
const PORT: number = parseInt(process.env.PORT || "3000", 10);
const TIMEOUT_MS: number = parseInt(process.env.TIMEOUT_MS || "5000", 10);
const TAX_RATE: number = parseFloat(process.env.TAX_RATE || "0.07");

Read convert an array to a dictionary in Typescript

Best Practices for TypeScript String to Number Conversion

Based on my experience, here are some best practices to follow:

  1. Choose the right method for your needs:
    • Use parseInt() when you specifically need integers
    • Use parseFloat() when decimal precision matters
    • Use Number() or unary + for general conversions
  2. Always provide a radix to parseInt():
   // Good practice
   const value = parseInt(string, 10);

   // Potentially problematic
   const value = parseInt(string);
  1. Handle potential NaN results:
   const numValue = Number(stringValue);
   if (isNaN(numValue)) {
     // Handle invalid input
   }
  1. Consider using default values:
   const age = Number(ageString) || 0; // Default to 0 if conversion fails
  1. Validate before conversion for better error messages:
   if (!/^\d+$/.test(stringValue)) {
     throw new Error("Invalid numeric input");
   }
   const numValue = Number(stringValue);

Performance Considerations

When working with large datasets or performance-critical applications, it’s worth noting the relative performance of different conversion methods. Generally, the unary plus operator (+) is the fastest method, followed closely by the Number() constructor. The parseInt() and parseFloat() functions have slightly more overhead but offer more control and predictability.

The performance difference is negligible for most applications, so I recommend choosing the method that best fits your specific requirements rather than optimizing prematurely.

Conclusion

In this tutorial, I explained how to convert strings to numbers in TypeScript using different methods such as Number(), parseInt(), parseFloat(), and the unary plus operator, etc. I hope all these real examples will help you!

You may also like:

Power Apps functions free pdf

30 Power Apps Functions

This free guide walks you through the 30 most-used Power Apps functions with real business examples, exact syntax, and results you can see.

Live Webinar

Quiz App Using SharePoint Framework (SPFx)

Learn to built a complete Quiz Management solution that enables admins to create and manage quizzes, categories, questions, and settings with an easy automated setup process in SharePoint. It also includes an interactive quiz experience for users and a powerful dashboard to track participation, analyze results, and view detailed performance reports with charts and answer insights.

📅 2nd June 2026 – 10:00 AM EST | 7:30 PM IST

Download User registration canvas app

DOWNLOAD USER REGISTRATION POWER APPS CANVAS APP

Download a fully functional Power Apps Canvas App (with Power Automate): User Registration App