How to convert a string to number in TypeScript?

In TypeScript, converting a string to a number can be done using several methods, similar to JavaScript. However, TypeScript adds static type checking, so you need to ensure the result is explicitly treated as a number. Here are the common approaches:

1. parseInt()

Converts a string to an integer (whole number).

const str: string = "123";
const num: number = parseInt(str, 10); // Always specify the radix (e.g., 10 for decimal)
console.log(num); // 123 (type: number)

Notes:

  • Use parseInt for integer values (ignores decimals).
  • The second argument (radix) specifies the numeral system (e.g., 2 for binary, 10 for decimal).
  • Returns NaN if parsing fails.

2. parseFloat()

Converts a string to a floating-point number (decimal).

const str: string = "123.45";
const num: number = parseFloat(str);
console.log(num); // 123.45 (type: number)

Notes:

  • Use for decimal numbers.
  • Returns NaN if parsing fails.
  • Ignores non-numeric characters after the number:
  parseFloat("123.45abc"); // 123.45

3. Number()

Explicitly converts a string to a number using the Number constructor.

const str: string = "123";
const num: number = Number(str);
console.log(num); // 123 (type: number)

Notes:

  • Returns NaN if the string isn’t purely numeric.
  • Handles decimals and scientific notation:
  Number("123.45"); // 123.45
  Number("1e5");    // 100000

4. Unary Plus Operator (+)

Short syntax for converting strings to numbers.

const str: string = "123";
const num: number = +str;
console.log(num); // 123 (type: number)

Notes:

  • Same behavior as Number().
  • Fails silently (returns NaN for invalid inputs).
  • Avoid using for non-trivial conversions to maintain readability.

5. Handling Edge Cases

Invalid Strings

Check for NaN using isNaN() or Number.isNaN():

const str: string = "abc123";
const num: number = parseInt(str, 10);

if (isNaN(num)) {
  console.log("Invalid number!");
}

Empty Strings or Whitespace

Number("");      // 0 (often unexpected!)
Number("   ");   // 0
parseInt(" ", 10); // NaN

Null/Undefined

Use optional chaining and nullish coalescing for safety:

const str: string | null = getStringFromAPI();
const num: number = Number(str ?? "0"); // Fallback to "0" if null/undefined

6. Type Assertions

TypeScript may require explicit type assertions if the conversion is indirect:

const str: string = "123";
const num = parseInt(str, 10) as number; // Explicit type assertion

7. Template Strings

Works the same as string conversion:

const str: string = `456`;
const num: number = +str; // 456

Best Practices

  1. Always validate input before conversion.
  2. Prefer parseInt/parseFloat for partial numeric strings (e.g., "123px").
  3. Use Number() or + for strict numeric-only strings.
  4. Handle NaN explicitly to avoid unexpected behavior.

Example Workflow

function convertToNumber(input: string): number | null {
  const num = Number(input);
  return Number.isNaN(num) ? null : num;
}

const result = convertToNumber("42");
if (result !== null) {
  console.log("Valid number:", result);
} else {
  console.log("Invalid input!");
}

Summary

MethodUse CaseReturns NaN?Handles Decimals?
parseInt()Integer conversion (e.g., "123")YesNo
parseFloat()Decimal conversion (e.g., "123.45")YesYes
Number()Strict numeric-only stringsYesYes
+ OperatorShort syntax for numeric stringsYesYes

Choose the method that best fits your use case and always validate the result!

Leave a Reply

Your email address will not be published. Required fields are marked *