Convert a String to a Number in TypeScript

avatar

Borislav Hadzhiev

Last updated: Feb 17, 2022

banner

Photo from Unsplash

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() object to convert a string to a number in TypeScript, e.g. const num1 = Number(str). When used as a function, Number(value) converts a string or other value to a number. If the value cannot be converted, it returns NaN (not a number).

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

We used the Number function to convert a string to a number.

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

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

It achieves the same goal as the Number function, 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.

Even if you pass a string that doesn't store a valid number to the Number function, you would get NaN (not a number) value back, which is also of type number.

index.ts
console.log(typeof NaN); // 👉️ "number"

If you try to convert a string that is not a valid number to a number using the Number function or the unary plus (+) operator, you would get a NaN (not a number) value back.

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 be using the parseInt() or parseFloat() functions.

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

Convert a String to a Number with parseInt or parseFloat #

Use the parseInt() function to convert a string to a number, e.g. const num1 = parseInt(str). The parseInt function takes the value to parse as a parameter 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

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 is able to infer the type of the variables to be numbers because even the type of NaN is a number.

It should be noted that if the first non-whitespace character of the string cannot be converted to a number, the parseInt() and parseFloat() functions would 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 #

To extract a number from a string in TypeScript, call the replace() method, e.g. str.replace(/\D/g, '') and pass the result to the Number() function. The replace method will replace all non-digit characters with an empty string and return the result.

index.ts
const str = 'hello 1234 world'; // 👇️ 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

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.

An edge case we have to handle is - if the string contains no digits at all, then we would be left with 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 does not store an empty string.

If you are sure that the string in your application will contain at least one number, or your use case is ok with converting an empty string to 0, you can simplify this a bit.

index.ts
const str = 'hello 1234 world'; // 👇️ const replaced: string const replaced = str.replace(/\D/g, ''); console.log(replaced); // 👉️ "1234" // 👇️ const num: number const num = Number(replaced); console.log(num); // 👉️ 1234

The first parameter we pass to the replace() method is a regular expression that we want to match in the string and the second parameter is the replacement for each match (an empty string).

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

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

This means that if the string only contains non-digit characters we would replace all of them with empty strings and the String.replace method would return an empty string.
Note that the String.replace method returns a new string, it does not mutate the original string. Strings are immutable in JavaScript.

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

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.