NeuroAgent

How to Convert String to Number in TypeScript

Learn how to convert strings to numbers in TypeScript using parseInt(), parseFloat(), Number(), and unary plus operator (+). Complete guide with examples and best practices for error handling.

Question

How to convert a string to number in TypeScript?

Given a string representation of a number, how can I convert it to number type in TypeScript?

typescript
var numberString: string = "1234";
var numberValue: number = /* what should I do with `numberString`? */;
NeuroAgent

To convert a string to a number in TypeScript, you can use several methods including parseInt() for integers, parseFloat() for decimal numbers, the Number() function, or the unary plus operator (+). Each method has specific use cases and behaviors that make them suitable for different scenarios in your code.


Contents


Overview of String to Number Conversion Methods

TypeScript, being a superset of JavaScript, inherits all the string-to-number conversion methods available in JavaScript. These methods serve different purposes and have unique behaviors that make them suitable for various conversion scenarios.

The main methods available are:

  1. parseInt() - Converts a string to an integer
  2. parseFloat() - Converts a string to a floating-point number
  3. Number() - Converts a string to a number (integer or float)
  4. Unary plus operator (+) - Quick conversion using the plus sign

Each method handles edge cases and non-numeric content differently, so choosing the right one depends on your specific requirements.


Using parseInt() for Integer Conversion

The parseInt() function converts a string to an integer by parsing it according to the specified radix (base). This method is ideal when you specifically need integer values.

Basic Syntax

typescript
parseInt(string, radix)

Examples

typescript
const str1: string = "123";
const num1: number = parseInt(str1, 10); // Returns: 123

const str2: string = "  456  ";
const num2: number = parseInt(str2, 10); // Returns: 456 (ignores whitespace)

const str3: string = "789px";
const num3: number = parseInt(str3, 10); // Returns: 789 (stops at non-numeric)

Key Behaviors

  • Stops at non-numeric characters: The function parses until it encounters a character that’s not part of the number representation
  • Handles whitespace: Leading and trailing whitespace is ignored
  • Radix is important: Always specify the radix (base) for predictable behavior

As Mozilla Developer Network explains, parseInt() takes in a string argument, parses it, and returns an integer equivalent according to the specified radix.

Common Use Cases

typescript
// Convert user input from form
const userInput: string = "42";
const age: number = parseInt(userInput, 10);

// Extract number from mixed content
const cssValue: string = "100px";
const pixels: number = parseInt(cssValue, 10);

Using parseFloat() for Decimal Conversion

The parseFloat() function converts a string to a floating-point number. Unlike parseInt(), it preserves decimal values and is perfect for handling monetary values, scientific calculations, or any scenario requiring decimal precision.

Basic Syntax

typescript
parseFloat(string)

Examples

typescript
const str1: string = "3.14";
const num1: number = parseFloat(str1); // Returns: 3.14

const str2: string = "  2.718  ";
const num2: number = parseFloat(str2); // Returns: 2.718 (ignores whitespace)

const str3: string = "99.99abc";
const num3: number = parseFloat(str3); // Returns: 99.99 (stops at non-numeric)

Key Behaviors

  • Preserves decimal precision: Unlike parseInt(), it doesn’t remove values after the decimal point
  • Stops at non-numeric characters: Similar to parseInt(), but recognizes decimal points
  • No radix parameter: Always parses as base 10 decimal

As stated in the official documentation, parseFloat() takes in a string and parses it returning a floating point number.

Common Use Cases

typescript
// Convert currency values
const priceStr: string = "19.99";
const price: number = parseFloat(priceStr);

// Handle scientific measurements
const temperatureStr: string = "98.6°F";
const temperature: number = parseFloat(temperatureStr);

// Parse CSS values with units
const widthStr: string = "50.5%";
const width: number = parseFloat(widthStr);

Using Number() Function

The Number() function constructor converts a string to a number, either integer or floating-point. This method is more strict than parseInt() and parseFloat() and returns NaN (Not a Number) for any invalid input.

Basic Syntax

typescript
Number(string)

Examples

typescript
const str1: string = "123";
const num1: number = Number(str1); // Returns: 123

const str2: string = "3.14";
const num2: number = Number(str2); // Returns: 3.14

const str3: string = "  456  ";
const num3: number = Number(str3); // Returns: 456 (trims whitespace)

const str4: string = "abc";
const num4: number = Number(str4); // Returns: NaN (invalid input)

Key Behaviors

  • Strict parsing: Returns NaN for any non-numeric content
  • Trims whitespace: Leading and trailing whitespace is removed
  • No partial parsing: Unlike parseInt() and parseFloat(), it doesn’t stop at non-numeric characters

As GeeksforGeeks explains, the Number() function is a global function that converts its argument to a number.

Common Use Cases

typescript
// Strict validation required
const userInput: string = "42";
const validatedNumber: number = Number(userInput);

// When you need to detect invalid conversions
const valueStr: string = "invalid";
const value: number = Number(valueStr);
if (isNaN(value)) {
    console.log("Invalid number format");
}

Using Unary Plus Operator (+)

The unary plus operator (+) provides a concise and often faster way to convert strings to numbers in TypeScript. This method is syntactically clean and performs similarly to the Number() function.

Basic Syntax

typescript
+string

Examples

typescript
const str1: string = "123";
const num1: number = +str1; // Returns: 123

const str2: string = "3.14";
const num2: number = +str2; // Returns: 3.14

const str3: string = "  456  ";
const num3: number = +str3; // Returns: 456 (trims whitespace)

const str4: string = "abc";
const num4: number = +str4; // Returns: NaN (invalid input)

Key Behaviors

  • Concise syntax: Very short and readable
  • Similar to Number(): Behaves like Number() function
  • Fast performance: Often faster than other methods in benchmarks

According to Geekflare, for instance, +"98" will evaluate to 98, and +"0" will evaluate to the number 0. Therefore, we can use the unary plus (+) operator to convert strings to numbers.

Common Use Cases

typescript
// Quick inline conversions
const result: number = +"42" + 10; // Returns: 52

// Array conversions
const stringNumbers: string[] = ["1", "2", "3"];
const numbers: number[] = stringNumbers.map(s => +s);

// Conditional conversions
const value: string = "123";
const numValue: number = +value || 0; // Fallback to 0 if invalid

Best Practices and Error Handling

When converting strings to numbers in TypeScript, it’s important to handle potential errors and edge cases appropriately.

Error Handling Strategies

1. Using isNaN() for Validation

typescript
function safeConvert(str: string): number {
    const num = parseFloat(str);
    return isNaN(num) ? 0 : num; // Fallback to 0 if invalid
}

// Usage
const result: number = safeConvert("invalid"); // Returns: 0

2. Using try-catch for Complex Cases

typescript
function robustConvert(str: string): number {
    try {
        return Number(str);
    } catch {
        return 0; // Fallback value
    }
}

3. Type Guards

typescript
function isNumber(str: string): str is string {
    return !isNaN(Number(str));
}

// Usage
if (isNumber(numberString)) {
    const numberValue = +numberString;
}

Performance Considerations

  • Unary plus (+) is generally the fastest method
  • Number() function is slightly slower but very readable
  • parseInt()/parseFloat() are slower due to additional parsing logic

Edge Cases to Consider

typescript
// Empty strings
const empty: number = Number(""); // Returns: 0

// Null/undefined
const nullValue: number = Number(null); // Returns: 0
const undefinedValue: number = Number(undefined); // Returns: NaN

// Boolean values
const trueValue: number = Number(true); // Returns: 1
const falseValue: number = Number(false); // Returns: 0

As TutorialsPoint explains, the parseInt function converts infinity, null, boolean values true and false, empty strings to NaN.


Complete Example Solutions

Solution to the Original Question

typescript
var numberString: string = "1234";
var numberValue: number = parseInt(numberString, 10); // Returns: 1234

// Alternative solutions:
var numberValue2: number = parseFloat(numberString); // Also works for integers
var numberValue3: number = Number(numberString); // Strict conversion
var numberValue4: number = +numberString; // Unary plus operator

Practical Examples

Example 1: Form Input Handling

typescript
function handleUserInput(input: string): number {
    // Using parseInt for age input
    const age: number = parseInt(input, 10);
    
    if (isNaN(age)) {
        throw new Error("Invalid age format");
    }
    
    return age;
}

// Usage
const userInput: string = "25";
const userAge: number = handleUserInput(userInput); // Returns: 25

Example 2: Currency Conversion

typescript
function parseCurrency(amount: string): number {
    // Remove currency symbols and commas
    const cleanAmount = amount.replace(/[^\d.]/g, '');
    return parseFloat(cleanAmount);
}

// Usage
const price: string = "$1,234.56";
const numericPrice: number = parseCurrency(price); // Returns: 1234.56

Example 3: Scientific Notation

typescript
function parseScientific(value: string): number {
    return Number(value); // Handles scientific notation like "1e3"
}

// Usage
const scientific: string = "2.5e2";
const result: number = parseScientific(scientific); // Returns: 250

Example 4: Array Conversion

typescript
function convertStringArray(numbers: string[]): number[] {
    return numbers.map(str => {
        // Use parseFloat for mixed integer/decimal arrays
        return parseFloat(str);
    });
}

// Usage
const stringNumbers: string[] = ["1", "2.5", "3", "4.75"];
const converted: number[] = convertStringArray(stringNumbers); // [1, 2.5, 3, 4.75]

Conclusion

Converting strings to numbers in TypeScript can be accomplished using several reliable methods, each with its own advantages:

  1. Use parseInt() when you specifically need integer values and want to extract numbers from mixed content
  2. Use parseFloat() for decimal values and when you need to preserve precision
  3. Use Number() for strict validation and when you need to detect invalid conversions
  4. Use unary plus (+) for concise, fast conversions when performance is critical

Always consider error handling and edge cases in your conversion logic, especially when dealing with user input or external data sources. The choice of method should be based on your specific requirements regarding validation, performance, and the nature of your input data.

For most practical applications, the unary plus operator or Number() function provide excellent balance between readability and performance, while parseInt() and parseFloat() remain valuable for parsing numbers from mixed content strings.


Sources

  1. How to Convert String to Number in TypeScript? - GeeksforGeeks
  2. How to convert a string to number in TypeScript? - Stack Overflow
  3. TypeScript String to Number: 5 Ways for Easy Conversion - Geekflare
  4. Convert String to Number in TypeScript [With Examples] - SP Guides
  5. Convert Strings to Numbers | TypeScript Guide by Convex
  6. Convert String to Number in Typescript - Tektutorialshub
  7. TypeScript string to number: Practical Conversion Guide - Dev Accelerate
  8. How to convert string to number in TypeScript? - Tutorialspoint
  9. Convert a String to a Number in TypeScript | bobbyhadz
  10. Top 4 Methods to Convert a String to Number in TypeScript - SQL Pey