Question
Given a string that represents a number, how can it be converted into the number type in TypeScript?
var numberString: string = "1234";
var numberValue: number = /* how should `numberString` be converted? */;
I want to understand the correct way to turn a numeric string into a TypeScript number, and which approaches are commonly used.
Short Answer
By the end of this page, you will understand how to convert strings to numbers in TypeScript using Number(), the unary + operator, parseInt(), and parseFloat(). You will also learn when to use each one, how invalid input behaves, and how to avoid common mistakes.
Concept
In TypeScript, the number type represents numeric values such as integers and decimals. A value like "1234" is still a string, even though it looks like a number. If you want to do numeric operations like addition, subtraction, comparison, or sorting, you usually need to convert that string into a real number.
TypeScript adds type checking, but it does not automatically transform string values into numbers for you. If data comes from:
- form inputs
- URL query parameters
- JSON payloads
- environment variables
- API responses
it often arrives as a string.
To convert a string to a number in TypeScript, the most common options are:
Number(value)+value(unary plus)parseInt(value, 10)for integersparseFloat(value)for decimals
These methods do not behave exactly the same way:
Number("123abc")returnsNaNparseInt("123abc", 10)returns123parseFloat("12.5px")returns12.5
That difference matters in real programs, especially when validating user input.
Mental Model
Think of a string as a label with characters printed on it, and a number as an actual quantity you can calculate with.
"123"is a text label that contains the characters1,2, and3123is a numeric value you can add, multiply, and compare mathematically
Converting a string to a number is like reading the label and turning it into a usable amount.
Different tools read the label differently:
Number()says: the whole label must be a valid numberparseInt()says: I will read from the start until the integer stopsparseFloat()says: I will read from the start until the decimal number stops- unary
+acts like a short form ofNumber()
So the best tool depends on how strict you want the conversion to be.
Syntax and Examples
Basic conversion
The most direct and readable approach is Number():
let numberString: string = "1234";
let numberValue: number = Number(numberString);
console.log(numberValue); // 1234
This converts the string into a number.
Using unary plus
A shorter version is unary plus:
let numberString: string = "1234";
let numberValue: number = +numberString;
console.log(numberValue); // 1234
This is common, but some beginners find Number() easier to read.
Converting integers with parseInt()
: = ;
: = (countString, );
.(count);
Step by Step Execution
Consider this example:
let input: string = "56.7";
let value: number = Number(input);
let doubled: number = value * 2;
console.log(doubled);
Step by step:
inputis assigned the string"56.7"Number(input)tries to convert the full string into a numeric value- The conversion succeeds, so
valuebecomes56.7 value * 2performs numeric multiplication, producing113.4console.log(doubled)prints113.4
Now compare it with invalid input:
let input: string = ;
: = (input);
.(value);
Real World Use Cases
String-to-number conversion appears everywhere in real software.
Form input values
HTML form fields usually return strings.
const ageInput = "25";
const age = Number(ageInput);
Query parameters
A URL may contain something like ?page=3.
const pageParam = "3";
const page = Number(pageParam);
Environment variables
Environment variables are typically strings.
const portString = "3000";
const port = Number(portString);
API and JSON data
Sometimes APIs send numeric values as strings.
const priceFromApi = "49.99";
const price = Number(priceFromApi);
Data cleanup scripts
CSV files often store everything as text.
Real Codebase Usage
In real projects, developers usually do more than just convert. They also validate.
Validation before using the number
function toNumber(value: string): number | null {
const result = Number(value);
return Number.isNaN(result) ? null : result;
}
This avoids using invalid numeric values by accident.
Guard clauses
function calculateDiscount(percentText: string): number {
const percent = Number(percentText);
if (Number.isNaN(percent)) {
throw new Error("Invalid discount percentage");
}
return percent / 100;
}
A guard clause stops bad data early.
Parsing configuration values
Common Mistakes
1. Forgetting that form input is a string
Broken example:
let a = "10";
let b = "20";
console.log(a + b); // "1020"
Why it happens:
+between strings concatenates text
Fix:
let a = Number("10");
let b = Number("20");
console.log(a + b); // 30
2. Not checking for NaN
Broken example:
let value = Number("abc");
console.log(value + 5); // NaN
Fix:
value = ();
(.(value)) {
.();
} {
.(value + );
}
Comparisons
| Method | Best for | Input must be fully numeric? | Example input | Result |
|---|---|---|---|---|
Number(value) | General numeric conversion | Yes | "123" | 123 |
+value | Short numeric conversion | Yes | "123" | 123 |
parseInt(value, 10) | Integers | No | "123abc" | 123 |
Cheat Sheet
// Convert string to number
const n1 = Number("123"); // 123
const n2 = +"123"; // 123
const n3 = parseInt("123", 10); // 123
const n4 = parseFloat("12.34"); // 12.34
Quick rules
Number("123")->123Number("12.5")->12.5Number("123abc")->NaN+"123"->123parseInt("123abc", 10)->123parseFloat("12.5px")->12.5
Check for invalid conversion
FAQ
How do I convert a string to a number in TypeScript?
Use Number(value) for a clear general-purpose conversion.
const value: number = Number("123");
Is unary plus valid in TypeScript?
Yes. Unary plus works in TypeScript the same way it works in JavaScript.
const value: number = +"123";
What is the difference between Number() and parseInt()?
Number() requires the full string to be numeric. parseInt() reads an integer from the start of the string and stops when it reaches an invalid character.
Why do I get NaN when converting a string?
You get NaN when the string cannot be converted into a valid number.
Number("hello"); // NaN
Mini Project
Description
Build a small TypeScript utility that safely converts user-provided text into numbers. This mirrors real applications where values come from forms, APIs, or config files as strings and must be validated before use.
Goal
Create a function that converts a string to a number and returns a safe result for valid and invalid input.
Requirements
- Create a function that accepts a
string. - Convert the string into a number.
- Return
nullwhen the input is not a valid number. - Demonstrate the function with integer, decimal, and invalid string inputs.
Keep learning
Related questions
Angular formGroup Error Explained: Fixing 'Can't bind to formGroup' in Reactive Forms
Learn why Angular shows 'Can't bind to formGroup' and how to fix it by importing ReactiveFormsModule correctly.
Fix "Element implicitly has an 'any' type" in TypeScript Object Indexing
Learn why TypeScript rejects string object indexing and how to fix it with keyof, unions, and typed object keys in React.
Fix "Property has no initializer" in Angular TypeScript Components
Learn why Angular TypeScript shows "Property has no initializer" and how to fix it using defaults, optional properties, or definite assignment.