How to convert string to number in TypeScript?

How to convert string to number in TypeScript?

Conversion of datatypes is a must irrespective of the programming language and any developer level. Various data types and functions are available to convert from one data type to another. But in this article, we restrict ourselves to one programming language and a single conversion i.e. convert string to number in TypeScript.


Getting Started🏃🏼

TypeScript is a superset of JavaScript, meaning you could perform all the capabilities of JS with additional support which provides a better developer experience. The main feature of TypeScript is the ability to add type safety functionality. Besides it has other features like optional static typing, early spotted bugs, predictability, readability, fast refactoring, etc.

With the context set of why TypeScript let’s focus on the conversion of string datatype to number the datatype. TypeScript emphasizes datatype a lot being a setback of JavaScript to completely mess up the codebase. Hence, dealing with type conversions is very necessary for TS and we are focussing it in detail.


string to number type conversion➡️

There are mainly three ways available to actually convert a string datatype to a number datatype. These are as follows:

Using Number function🔢

It is useful in converting most of the fundamental datatypes to an number also returns NaN if the conversion is not possible. Let’s see the implementation of different types of conversions possible:

// Using `Number` function

console.log(Number('1'))            // 1
console.log(Number('5103.21'))      // 5103.21
console.log(Number('7CAF'))         // NaN
console.log(Number(''))             // 0
console.log(Number(false))          // 0
console.log(Number(true))           // 1
console.log(Number(undefined))      // NaN
console.log(Number(Infinity))       // Infinity
console.log(Number('2,05,000'))     // NaN
console.log(Number('2.05e5'))       // 205000
console.log(Number('0x75'))         // 117
console.log(Number('A-412'))        // NaN
Code language: TypeScript (typescript)

Let’s go through each of the cases: In the first two cases, the strings are automatically converted to Number. Then a mix of alphabets and integers resulted in a NaN, this way we don’t get any errors and the code runs smoothly. Then an empty string and false evaluates to 0. Then boolean true evaluates to 1. Conversion of undefined evaluates to NaN. Then converting a string of numbers written in pen-paper format results again in NaN. The exponential way of representing too works well. In the penultimate case, the integer 75 is prefixed with 0x which refers to hexadecimal notation. Then when it converts to decimal then we get its decimal equivalent in our case it is 175 by the normal decimal conversion techniques. Finally having special characters leads to NaN.

Using parseInt function🔎

Here we are using a function named as parseInt() that has similar functionality as the Number() but its working is quite different. We are going to see the way it works against Number() function. Let’s see the implementation:

// Using `parseInt()` function

console.log(parseInt('1'))            // 1
console.log(parseInt('5103.21'))      // 5103
console.log(parseInt('7CAF'))         // 7
console.log(parseInt('C7AF'))         // NaN

console.log(parseInt('2,05,000'))     // 2
console.log(parseInt('2.05e5'))       // 2
console.log(parseInt(''))             // NaN
console.log(parseInt('0x75'))         // 117
Code language: TypeScript (typescript)

Let’s run through every test case to get a better understanding. The first case speaks for itself. In the second case, the values after the decimal point ( . ) are ignored. Then while using a combination of alphabets and integers it converts to an integer from the beginning until the first occurrence of a string. If there are no such cases then it returns NaN. The cases from the third to the sixth justify what is said above. Then as in the previous output, in the next two cases, an empty string and a hexadecimal results in a NaN and its decimal equivalent. Hope the way Number and parseInt works are clear.

Using unary(+) operator➕

The unary operator + can be compared with Number function as it resembles it in most cases except a few edge cases. Let’s see it in action:

// Using `Unary` function

console.log(+'1')            // 1
console.log(+'5103.21')      // 5103.21
console.log(+'7CAF')         // Nan
console.log(+'')             // 0
console.log(+false)          // 0
console.log(+true)           // 1
console.log(+Infinity)       // Infinity
console.log(+'2.05e5')       // 205000
console.log(+'1,95,000')     // NaN
console.log(+'0x75')         // 117
console.log(+'A-412')        // NaN

Code language: TypeScript (typescript)

Let’s dry-run through every case to understand its functionality. The first six cases resemble Number the function’s functionality. But we cannot use the undefined conversion using the + operator. The remaining cases have worked the same way as number works. The major difference lies in the conversion of undefined type.

Therefore we have seen the different ways how we can convert a string to a number, and a few other types as well in TypeScript. If you feel there is anything confusing or not understandable feel free to give TS docs a read. It’s worth the time spent, trust me. Finally heading towards the conclusion.


Conclusion🔚

Let’s finally conclude by listing the learning of the article:

  • Emphasize the importance of the conversion of data types.
  • Learned about TypeScript and conversion in TypeScript
  • Detailed overview of three ways to conversion with examples.

The code that is used above is available as a codedamn playground for reference. Feel free to fork it and play around with different conversions which are available in individual files starting with conversion- and with the extension .ts. There is the same file name with .js an extension of JavaScript that ultimately TS gets converted to JavaScript for execution in the development or production environment.

You can learn more about TS through the course TypeScript Fundamentals – Zero to Expert offered by Codedamn to dig deeper into TypeScript.

Sharing is caring

Did you like what Sriniketh J wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far