TypeScript
Programming
String Conversion
Web Development
Coding Tutorial

How to convert a string to number in TypeScript?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

TypeScript provides several ways to convert a string to a number: Number() (full string conversion), parseInt() (integer parsing with radix), parseFloat() (decimal parsing), and the unary + operator (shorthand for Number()). The best choice depends on your input format and error handling needs. Number() is strictest — it returns NaN for any non-numeric string. parseInt() and parseFloat() are more lenient — they parse as much as they can from the start of the string. Always validate the result with isNaN() or Number.isFinite() to handle invalid inputs safely.

Number() Function

typescript
1let str: string = "123";
2let num: number = Number(str);
3console.log(num);        // 123
4console.log(typeof num); // "number"
5
6// Handles decimals
7Number("3.14");          // 3.14
8
9// Handles whitespace
10Number("  42  ");        // 42
11
12// Returns NaN for non-numeric strings
13Number("hello");         // NaN
14Number("12abc");         // NaN (strict — entire string must be numeric)
15Number("");              // 0 (empty string converts to 0)
16Number(null);            // 0
17Number(undefined);       // NaN

Number() attempts to convert the entire string. If any part is non-numeric (except leading/trailing whitespace), it returns NaN. This makes it the safest choice for strict validation.

parseInt() Function

typescript
1let str: string = "42";
2let num: number = parseInt(str, 10);  // Always specify radix
3console.log(num);  // 42
4
5// Parses from the start, ignoring trailing non-numeric characters
6parseInt("123abc", 10);  // 123
7parseInt("3.14", 10);    // 3 (drops decimal part)
8parseInt("0xFF", 16);    // 255 (hexadecimal)
9parseInt("010", 10);     // 10 (radix 10 prevents octal interpretation)
10parseInt("010", 8);      // 8 (octal)
11
12// Returns NaN if string doesn't start with a number
13parseInt("abc", 10);     // NaN
14parseInt("", 10);        // NaN (unlike Number("") which returns 0)

parseInt() parses an integer from the beginning of the string. The second argument (radix) specifies the number base. Always pass 10 for decimal parsing to avoid legacy octal behavior.

parseFloat() Function

typescript
1let str: string = "3.14159";
2let num: number = parseFloat(str);
3console.log(num);  // 3.14159
4
5// Parses from the start
6parseFloat("42.5px");    // 42.5
7parseFloat("1.2e3");     // 1200 (scientific notation)
8parseFloat(".5");        // 0.5
9
10// Returns NaN for non-numeric start
11parseFloat("abc");       // NaN
12parseFloat("");          // NaN

parseFloat() is similar to parseInt() but preserves the decimal part. It does not accept a radix parameter — it always parses base-10.

Unary Plus Operator

typescript
1let str: string = "99";
2let num: number = +str;
3console.log(num);  // 99
4
5// Equivalent to Number()
6+("3.14");       // 3.14
7+("hello");      // NaN
8+("");           // 0
9+("  42  ");     // 42
10
11// Common in TypeScript/JavaScript codebases
12const price: number = +inputElement.value;

The + prefix operator is a shorthand for Number(). It is concise but can be less readable, especially for developers unfamiliar with the idiom.

Type-Safe Conversion Function

typescript
1function toNumber(value: string): number | null {
2    const num = Number(value);
3    return Number.isFinite(num) ? num : null;
4}
5
6// Returns number or null for invalid input
7toNumber("42");      // 42
8toNumber("3.14");    // 3.14
9toNumber("hello");   // null
10toNumber("");        // null (Number("") is 0, but isFinite filters it)
11
12// Stricter: also reject empty and whitespace-only strings
13function strictToNumber(value: string): number | null {
14    if (value.trim() === "") return null;
15    const num = Number(value);
16    return Number.isNaN(num) ? null : num;
17}
18
19strictToNumber("0");     // 0
20strictToNumber("");      // null
21strictToNumber("  ");    // null
22strictToNumber("42");    // 42

Handling User Input

typescript
1// Form input is always a string
2function handleFormSubmit(formData: { age: string; price: string }) {
3    const age = parseInt(formData.age, 10);
4    const price = parseFloat(formData.price);
5
6    if (isNaN(age) || age < 0 || age > 150) {
7        throw new Error("Invalid age");
8    }
9
10    if (isNaN(price) || price < 0) {
11        throw new Error("Invalid price");
12    }
13
14    return { age, price };
15}
16
17// API response parsing
18interface ApiResponse {
19    id: string;    // API returns numbers as strings
20    total: string;
21}
22
23function parseResponse(data: ApiResponse) {
24    return {
25        id: Number(data.id),
26        total: Number(data.total)
27    };
28}

Comparison Table

typescript
1const input = "42.5abc";
2
3Number(input);          // NaN     (strict: entire string must be numeric)
4parseInt(input, 10);    // 42      (parses integer from start)
5parseFloat(input);      // 42.5    (parses float from start)
6+(input);               // NaN     (same as Number())
Method"123""3.14""12abc"""" 42 "
Number()1233.14NaN042
parseInt(,10)123312NaN42
parseFloat()1233.1412NaN42
+1233.14NaN042

Template Literal and String Concatenation

typescript
1// Watch out: + with string operand concatenates instead of adding
2const a: string = "5";
3const b: number = 10;
4
5console.log(a + b);     // "510" (string concatenation!)
6console.log(+a + b);    // 15   (numeric addition)
7console.log(Number(a) + b);  // 15
8
9// TypeScript catches some of these
10const result: number = a + b;  // Error: Type 'string' is not assignable to 'number'

Common Pitfalls

  • Forgetting the radix in parseInt(): parseInt("010") returns 8 in older JavaScript engines (octal interpretation). Always pass the radix explicitly: parseInt("010", 10) returns 10. TypeScript does not warn about missing radix by default.
  • Number("") returns 0, not NaN: An empty string converts to 0 with Number() and the + operator. If your code treats 0 as a valid input, empty strings silently pass validation. Check for empty strings before converting.
  • Using isNaN() vs Number.isNaN(): Global isNaN() coerces its argument to a number first: isNaN("hello") returns true. Number.isNaN() does not coerce: Number.isNaN("hello") returns false. Use Number.isNaN(Number(value)) for type-safe checking.
  • String concatenation instead of addition: "5" + 10 produces "510" (concatenation), not 15 (addition). When one operand is a string, + performs concatenation. Convert the string to a number first with Number(), +, or parseInt().
  • Precision loss with large numbers: Number("9007199254740993") returns 9007199254740992 due to IEEE 754 double-precision limits. For integers larger than Number.MAX_SAFE_INTEGER (2^53 - 1), use BigInt("9007199254740993") instead.

Summary

  • Use Number(str) for strict conversion that rejects partially numeric strings like "12abc"
  • Use parseInt(str, 10) for integer parsing that tolerates trailing characters
  • Use parseFloat(str) for decimal parsing from the start of a string
  • The unary +str is shorthand for Number(str) — concise but less readable
  • Always validate the result with Number.isNaN() or Number.isFinite() before using it
  • Always pass the radix (10) to parseInt() to avoid octal interpretation

Course illustration
Course illustration

All Rights Reserved.