3 Ways to Convert String to Number in TypeScript

TypeScript, a powerful superset of JavaScript, offers a plethora of features that enhance the developer experience. One of the fundamental aspects of TypeScript is its emphasis on type safety, which ensures code reliability and maintainability. In this guide, we'll delve deep into the intricacies of converting strings to numbers in TypeScript, providing you with a thorough understanding of the various methods available.

graph TD A[String] --> B["Number() Function"] A --> C["parseInt() Function"] A --> D[Unary + Operator] B --> E[Number] C --> E D --> E

Why TypeScript?

TypeScript is not just JavaScript with types. It brings along a suite of features that make development smoother:

  • Type Safety: TypeScript's static typing feature catches errors early, making the codebase more robust.
  • Readability: With types, the code becomes self-documenting, making it easier for developers to understand the intent.
  • Refactoring: TypeScript's tooling support ensures that refactoring is a breeze, reducing the chances of introducing bugs.

With TypeScript's significance established, let's dive into the core topic of this article: converting strings to numbers.

Methods for String to Number Conversion in TypeScript

There are primarily three techniques to transform a string into a number in TypeScript:

  1. Using the Number() function
  2. Utilizing the parseInt() function
  3. Employing the unary + operator

1. The Number() Function

The Number() function is versatile, capable of converting various data types to numbers. If a conversion isn't feasible, it returns NaN (Not a Number). Here's a demonstration:

TypeScript
console.log(Number('1'));          // Outputs: 1
console.log(Number('5103.21'));   // Outputs: 5103.21
console.log(Number('7CAF'));      // Outputs: NaN
console.log(Number('2.05e5'));    // Outputs: 205000

2. The parseInt() Function

The parseInt() function, while similar to Number(), operates differently. It parses a string from left to right until it encounters a character that isn't a number, then stops:

TypeScript
console.log(parseInt('5103.21')); // Outputs: 5103
console.log(parseInt('7CAF'));    // Outputs: 7
console.log(parseInt('C7AF'));    // Outputs: NaN

3. The Unary + Operator

The unary + operator is akin to the Number() function in many scenarios, with a few exceptions:

TypeScript
console.log(+'5103.21');  // Outputs: 5103.21
console.log(+'7CAF');     // Outputs: NaN

Handling Special Cases

In TypeScript, certain values might not behave as you'd expect when attempting to convert them:

  • An empty string, when passed to the Number() function or the unary + operator, evaluates to 0. However, parseInt() returns NaN.
  • The value Infinity, when converted using any of the methods, remains Infinity.
  • Hexadecimal values, prefixed with 0x, are correctly parsed by all three methods. For instance, Number('0x75') and parseInt('0x75') both return 117.

FAQs

Q1: Why does parseInt('7CAF') return 7 and not NaN?
Answer: The parseInt() function parses a string from left to right and stops when it encounters a non-numeric character. In this case, it reads the number 7 and stops at the letter C.

Q2: How does TypeScript handle the conversion of boolean values to numbers?
Answer: In TypeScript, the boolean value true converts to 1, and false converts to 0 when using the Number() function or the unary + operator.

Q3: Are there any performance differences between the three conversion methods?
Answer: In most scenarios, the performance differences are negligible. However, for large-scale applications or repeated conversions, it's advisable to benchmark the methods to determine the most efficient one for your use case.

Q4: How does TypeScript handle the conversion of undefined?
Answer: When attempting to convert undefined using the Number() function, the result is NaN. The unary + operator doesn't support the conversion of undefined.

Q5: Can I use these conversion methods in regular JavaScript?
Answer: Yes, these methods are not exclusive to TypeScript. They can be used in regular JavaScript as well, with similar results.

Conclusion

Understanding data type conversions, especially in a type-centric language like TypeScript, is crucial. This guide provided a detailed exploration of the methods available for converting strings to numbers in TypeScript. By mastering these techniques, developers can ensure code reliability and maintainability.

Author