How to Convert a String to a Number in TypeScript: Top Errors and How to Avoid Them

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction: Why a Simple Task Breaks Code

\n\n

Every developer working with TypeScript eventually faces the task: "How to convert a string to a number?". It seems like it couldn't be simpler. But this seemingly trivial operation becomes the source of dozens of bugs, especially at the intersection of frontend and backend, where data comes from input forms, APIs, or CSV parsing.

\n\n

On Stack Overflow, the question "How to convert a string to number in TypeScript?" has garnered tens of thousands of views. And this is no coincidence. Developers get lost in the nuances: NaN, parseInt vs Number(), loss of precision, and unexpected behavior with empty strings. In this article, we will analyze the top errors when converting a string to a number in TypeScript and show how to avoid them. You will learn which method to choose for a specific task and how to write truly reliable code.

\n\n

Main Ways to Convert a String to a Number in TypeScript

\n\n

Before discussing errors, let's recall the tools available in a TypeScript developer's arsenal. Each behaves differently, and choosing the wrong method is the first and main mistake.

\n\n

1. The Number() Function

\n

The most obvious way. Number(value) attempts to convert the passed value to a number. If this is impossible, it returns NaN.

\n\n
const str: string = "42";\nconst num: number = Number(str);\nconsole.log(num); // 42\n\nconst invalid: string = "hello";\nconst badNum: number = Number(invalid);\nconsole.log(badNum); // NaN
\n\n

2. Unary Plus (+)

\n

A short syntax that does the same thing as Number(). It's concise but can be confusing for beginners.

\n\n
const price: string = "99.99";\nconst numericPrice: number = +price;\nconsole.log(numericPrice); // 99.99\n\nconst empty: string = "";\nconst zero: number = +empty;\nconsole.log(zero); // 0 — caution, this is a common pitfall!
\n\n

3. parseInt() and parseFloat()

\n

Specialized functions for parsing integers and floating-point numbers. They "extract" the numeric part from the string, ignoring subsequent characters.

\n\n
const userInput: string = "123px";\nconst width: number = parseInt(userInput, 10);\nconsole.log(width); // 123 — the 'px' characters are discarded\n\nconst height: string = "45.67em";\nconst parsedHeight: number = parseFloat(height);\nconsole.log(parsedHeight); // 45.67
\n\n

4. Bitwise Operators (~~, | 0)

\n

An exotic method that came from JavaScript. It only works for integers and discards the fractional part.

\n\n
const str: string = "7.8";\nconst result: number = ~~str;\nconsole.log(result); // 7 — fractional part is lost
\n\n

Top 5 Errors When Converting a String to a Number in TypeScript

\n\n

Now that we've covered the tools, let's look at where developers most often stumble. These errors are real "rakes" that even experienced programmers step on.

\n\n

Error #1: Ignoring NaN

\n

The most common mistake is not checking the result for NaN. TypeScript will not throw an error if you use NaN in arithmetic operations or comparisons, but the result will be unexpected.

\n\n
const input: string = "not a number";\nconst value: number = Number(input);\n\n// Error: NaN participates in calculations\nconst total = value + 10;\nconsole.log(total); // NaN\n\n// Comparison with NaN is always false\nif (value === NaN) {\n  console.log("This will never work");\n}
\n\n

How to avoid: Always use isNaN() or Number.isNaN() for checking. The second option is preferable as it does not coerce non-numeric types.

\n\n
if (Number.isNaN(value)) {\n  console.error("Not a number entered");\n  // You can return a default value or show an error                

Blogs

Book Recommendations