Typescript convert string to number

How to convert a String to a Number in TypeScript

TypeScript is a strongly typed language, which means we have to give things a little more thought when converting between them. Fortunately, converting a string to a number is pretty easy in TypeScript.

Converting a String to a Number in TypeScript

If we’re using integers, the easiest way to convert a string into a number is to simply use the unary ( + ) operator. Here is an example using a simple integer:

let someString:string = "4245" let myNumber:number = +someString;  // Returns 4246 console.log(myNumber + 1); 

We can also just use or parseInt for number-like integer strings:

let someString:string = "4245" let myNumber:number = parseInt(someString);  // Returns 4246 console.log(myNumber + 1); 

Converting Decimals

Unfortunately this method won’t work very well for decimals, as + and parseInt deal only with integers. If we want to convert a decimal-like string to a number in TypeScript, we can use parseFloat , just like normal Javascript:

let someString:string = "4245.1234" let myNumber:number = parseFloat(someString);  // Returns 4246.1234 console.log(myNumber + 1); 

Number function

We can also use the Number function to convert number-like strings into numbers. This will work with both integers and decimals:

let someString:string = "4245" let myNumber:number = Number(someString);  // Returns 4246.1234 console.log(myNumber + 1); 

More Tips and Tricks for Typescript

Источник

Typescript convert string to number

Last updated: Jan 20, 2023
Reading time · 4 min

banner

# Table of Contents

# 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.

Copied!
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() constructor to convert a string 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.

Copied!
const str = '1234'; const num2 = +str; console.log(num2); // 👉️ 1234

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.

Copied!
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.

Читайте также:  Основные паттерны ооп java

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 .

Copied!
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.

Copied!
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 can infer the type of the variables to be numbers 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).

Copied!
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.

Copied!
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

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.

Copied!
// 👇️ 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.

Copied!
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

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.

Источник

Convert String to Number in Typescript

There are several ways you can convert Typescript String to Number. The best way is to make use of the unary plus + operator or the Number global function. You can make use of the parseint or parsefloat functions. The following examples show how to make use of these functions.

Unary plus (+)

The Unary plus (+) operator converts all string representations of numbers, boolean values(true and false), and null to numbers. If the operand cannot be converted into a number, the unary plus operator will return NaN .

The following are some of the examples

  1. Tries to convert any string to a number
  2. It converts empty string / Null to 0
  3. True is 1 and False is 0
  4. Converts Octal/Hexa numbers to decimal.
  5. Works correctly on scientific notation numbers.
  6. In case it fails to convert, then returns NaN

Parseint

The parseint function parses an string and returns an integer. The syntax of the parseInt is as follows. If you do not provide the radix then it assumes the Hexadecimal number.

  1. Tries to convert any string to a integer and not to floating number
  2. Converts empty strings, null, infinity, True & false to a NaN
  3. If the string begins with 0x then it treats it a Hexadecimal number.
  4. It does not recognize the octal number that begins with 0o
  5. The older browsers will treat the number starting with 0 as Octal.
  6. Ignores the Leading & trailing spaces
  7. If only the initial part of the string is a number, then it converts into number and ignores the rest.

You can make use of the radix . The radix can be from 2 to 36. Use 2 for binary, 8 for octal, 10 for decimal & 16 for HexaDecimal number.

Parsefloat

ParseFloat is another way to convert string to a number.

  1. Tries to convert any string to a decimal or an integer number
  2. Converts empty strings, null, True & false to a NaN
  3. Returns infinity as it is.
  4. It the string begins with 0x or 0o it returns zero. Does not recognize Hexa decimal or octal numbers
  5. Ignores the Leading & trailing spaces
  6. If only the initial part of the string is a number, then it converts into number and ignores the rest.

Number global function

You can also use the Number global function. It is very similar to unary plus ( + )

  1. Tries to convert any string to a number
  2. It converts empty string / Null to 0
  3. True is 1 and False is 0
  4. Converts Octal/Hexa numbers to decimal.
  5. Works correctly on scientific notation numbers.
  6. In case it fails to convert, then returns NaN

Check for NaN

The string to number operation may result in a NaN . The NaN stands for not a number. It is the result of numerical operations, where the result is not a number. Hence always check if the value is NaN using the isNaN method after the conversion.

Источник

How To Convert A String To A Number In TypeScript?

Tim Mouskhelichvili

When coding with TypeScript, developers sometimes need to convert a string to a number. Luckily, JavaScript provides many different ways to do it that you can also use in TypeScript.

The easiest way to cast a string to a number in TypeScript is to use the Number constructor like so:

typescriptconst myString = '444222'; const myNumber = Number(myString); // Outputs: 444222 console.log(myNumber);

This article will go through different methods of converting a string to a number in TypeScript and show how to use each.

Method #1 — Using the Number constructor

Perhaps, the easiest way to cast a string to a number is to use the JavaScript Number constructor.

This function works with integers and with floats.

typescript// Outputs: 9999 console.log(Number('9999')); // Outputs: NaN console.log(Number('asdqwewe2'));

Note: If the function cannot cast the string into a number, it will return a NaN (not a number).

Method #2 — Using the parseInt function

The JavaScript parseInt function only works with integers.

If you attempt to pass a string with floating-point values, they will be cut off.

typescript// Outputs: 55 console.log(parseInt('55')); // Outputs: 23 console.log(parseInt('23.22'));

The best Web Development course in 2023! 👉 Learn Web Development

Method #3 — Using the parseFloat function

The parseFloat function behaves the same as the parseInt function, except it accepts floating point values.

typescript// Outputs: 55 console.log(parseFloat('55')); // Outputs: 23.22 console.log(parseFloat('23.22')); 

Method #4 — Using multiplication by one

One less known JavaScript trick is to multiple a string by one, which converts the string into a number.

Here is how to do in TypeScript:

typescript// Outputs: 2323.12 console.log("2323.12" as any * 1); // Outputs: 444 console.log("444" as any * 1); // Outputs: -55 console.log("-55" as any * 1);

As you can see, you must first cast the string to an any type.

Otherwise, the TypeScript compiler will complain.

Method #5 — Using the double tilde operator

Using the double tilde operator, you can convert a string to a number in TypeScript.

However, values after the decimal point will be cut off.

typescript// Outputs: 2323 console.log(~~"2323.12"); // Outputs: 444 console.log(~~"444");

Final thoughts

As you can see, you have plenty of methods to choose from when casting a string to a number.

When it comes to me, most of the time, I use the Number constructor.

typescript convert string to number

Here are some other TypeScript tutorials for you to enjoy:

The best Web Development course in 2023! 👉 Learn Web Development

Tim Mouskhelichvili

Hello! I am Tim Mouskhelichvili, a Freelance Developer & Consultant from Montreal, Canada. I specialize in React, Node.js & TypeScript application development. If you need help on a project, please reach out, and let’s work together.

Источник

Оцените статью