Convert a String to a Number in TypeScript

avatar
Borislav Hadzhiev

Last updated: Feb 26, 2024
4 min

banner

# Table of Contents

  1. Convert a String to a Number in TypeScript
  2. Convert a String to a Number with parseInt or parseFloat
  3. Extract a Number from a String in TypeScript

# Convert a String to a Number in TypeScript

Use the Number() constructor to convert a string to a number in TypeScript.

When used as a function, Number(value) converts a string or other value to a number. If the value cannot be converted, NaN is returned.

index.ts
const str = '1234'; // ๐Ÿ‘‡๏ธ const num1: number const num1 = Number(str); console.log(num1); // ๐Ÿ‘‰๏ธ 1234 // ๐Ÿ‘‡๏ธ const num2: number const num2 = +str; console.log(num2); // ๐Ÿ‘‰๏ธ 1234

convert string to number in typescript

The code for this article is available on GitHub

We used the Number() constructor to convert a string to a number.

The only parameter the function takes is the value we want to convert to a number.

# Using the unary plus (+) operator

You might also see developers use the unary plus (+) operator to convert a string to a number.

index.ts
const str = '1234'; const num2 = +str; console.log(num2); // ๐Ÿ‘‰๏ธ 1234

using unary plus operator

The code for this article is available on GitHub

It achieves the same result but might be confusing to readers of your code who are not familiar with the unary plus (+) operator.

You should avoid using the unary plus (+) operator when adding numbers because it makes your code look quite strange.

index.ts
const str = '1234'; const num2 = 6 + +str; console.log(num2); // ๐Ÿ‘‰๏ธ 1240

The first plus is the addition operator and the second one is used to convert the string to a number.

Both approaches have correct typing and allow TypeScript to infer that the variable stores a number.

Passing a value that is not a valid number to the Number() constructor returns NaN.

index.ts
const str = '1234test'; const num1 = Number(str); console.log(num1); // ๐Ÿ‘‰๏ธ NaN const num2 = +str; console.log(num2); // ๐Ÿ‘‰๏ธ NaN

In this scenario, you should use the parseInt() or parseFloat() functions.

Like the names suggest, parseInt converts a string to an integer, whereas parseFloat converts a string to a floating-point number.

# Convert a String to a Number with parseInt or parseFloat

The parseInt function takes a string and returns an integer parsed from the provided string.

index.ts
const str = '1234.5test'; // ๐Ÿ‘‡๏ธ const num1: number const num1 = parseInt(str); console.log(num1); // ๐Ÿ‘‰๏ธ 1234 // ๐Ÿ‘‡๏ธ const num2: number const num2 = parseFloat(str); console.log(num2); // ๐Ÿ‘‰๏ธ 1234.5

convert string to number with parse int and parse float

The code for this article is available on GitHub

The only parameter we passed to the parseInt function is the string we want to convert to an integer.

The second example uses the parseFloat function to convert a string to a floating-point number.

TypeScript can infer the type of the variables to be number because even NaN is of type number.

If the first non-whitespace character of the string cannot be converted to a number, the parseInt() and parseFloat() functions return NaN (not a number).

index.ts
const str = 'test1234.5test'; const num1 = parseInt(str); console.log(num1); // ๐Ÿ‘‰๏ธ NaN const num2 = parseFloat(str); console.log(num2); // ๐Ÿ‘‰๏ธ NaN

The parseInt() and parseFloat() functions are able to parse a number from a string if the string starts with a valid number.

However, if the first non-whitespace character of the string cannot be converted to a number, the methods short-circuit returning NaN.

If this is the situation you're in, you need to extract a number from a string using the replace() method.

# Extract a Number from a String in TypeScript

The replace method is used to replace all non-digit characters with an empty string and return the result.

index.ts
const str = 'bobby 1234 hadz'; // ๐Ÿ‘‡๏ธ const replaced: string const replaced = str.replace(/\D/g, ''); console.log(replaced); // ๐Ÿ‘‰๏ธ "1234" let num: number | undefined; if (replaced !== '') { num = Number(replaced); } // ๐Ÿ‘‡๏ธ let num: number | undefined console.log(num); // ๐Ÿ‘‰๏ธ 1234

extract number from string in typescript

The code for this article is available on GitHub

The example uses the String.replace method to replace all non-digit characters in the string with an empty string.

This effectively removes all non-digit characters from the string.

If the string contains no digits at all, we would get an empty string.

Converting an empty string to a number returns 0 which might not be what you want.

index.ts
// ๐Ÿ‘‡๏ธ 0 console.log(Number(''));

This is why we set the type of the num variable to number | undefined and we're only setting the variable to a number if the replaced variable doesn't store an empty string.

You can simplify this a bit if you are sure that the string in your application will contain at least one number.

index.ts
const str = 'bobby 1234 hadz'; // ๐Ÿ‘‡๏ธ const replaced: string const replaced = str.replace(/\D/g, ''); console.log(replaced); // ๐Ÿ‘‰๏ธ "1234" // ๐Ÿ‘‡๏ธ const num: number const num = Number(replaced); console.log(num); // ๐Ÿ‘‰๏ธ 1234

if you are sure the string will contain at least one number

The first parameter we passed to the replace() method is a regular expression that we want to match in the string

The second parameter is the replacement for each match (an empty string).

The \D character matches a character that is NOT a digit.

We added the g (global) flag to match all non-digit characters and replace them with an empty string.

You should only use this approach if the parseInt() and parseFloat() functions are insufficient as it is always better to leverage built-in functions when possible.

If you need to convert a number to a string, check out the following article.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev