Question

How to Convert a String to a Number in TypeScript

typescriptjavascript

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 integers
  • parseFloat(value) for decimals

These methods do not behave exactly the same way:

  • Number("123abc") returns NaN
  • parseInt("123abc", 10) returns 123
  • parseFloat("12.5px") returns 12.5

That difference matters in real programs, especially when validating user input.

A key idea: conversion may fail. When it fails, JavaScript and TypeScript usually produce NaN (Not a Number). NaN is still of type number, so you should check for it with Number.isNaN(...) when input may be invalid.

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 characters 1, 2, and 3
  • 123 is 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 number
  • parseInt() says: I will read from the start until the integer stops
  • parseFloat() says: I will read from the start until the decimal number stops
  • unary + acts like a short form of Number()

So the best tool depends on how strict you want the conversion to be.

Take Quiz

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()

let countString: string = "42";
let count: number = parseInt(countString, 10);

console.log(count); // 42

Always pass 10 as the radix when you want base-10 integers.

Converting decimals with parseFloat()

let priceString: string = "19.99";
let price: number = parseFloat(priceString);

console.log(price); // 19.99

Invalid input

let badValue: string = "hello";
let result: number = Number(badValue);

console.log(result); // NaN
console.log(Number.isNaN(result)); // true

Recommended beginner rule

  • Use Number() when the entire string should be numeric
  • Use parseInt() when you specifically want an integer from text
  • Use parseFloat() when you specifically want a decimal number from text

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:

  1. input is assigned the string "56.7"
  2. Number(input) tries to convert the full string into a numeric value
  3. The conversion succeeds, so value becomes 56.7
  4. value * 2 performs numeric multiplication, producing 113.4
  5. console.log(doubled) prints 113.4

Now compare it with invalid input:

let input: string = "56.7abc";
let value: number = Number(input);

console.log(value); // NaN

What happens here:

  1. input contains extra non-numeric characters
  2. Number(input) requires the whole string to be a valid number
  3. Because "56.7abc" is not fully numeric, the result is NaN

Now compare that with parseFloat():

let input: string = "56.7abc";
let value: number = parseFloat(input);

console.log(value); // 56.7

Here, parseFloat() reads the number from the beginning and stops when it reaches a.

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.

const rowValue = "1001";
const id = Number(rowValue);
Take Quiz

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

function getTimeout(configValue: string | undefined): number {
  const timeout = Number(configValue);

  if (!configValue || Number.isNaN(timeout)) {
    return 5000;
  }

  return timeout;
}

Mapping string arrays to numbers

const values = ["1", "2", "3"];
const numbers = values.map(Number);

console.log(numbers); // [1, 2, 3]

This pattern is common when processing data.

Error handling for user input

In user-facing apps, invalid input is often handled with:

  • error messages
  • fallback values
  • disabled submit buttons
  • validation schemas

The conversion itself is simple, but safe usage is what matters in production code.

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:

let value = Number("abc");

if (Number.isNaN(value)) {
  console.log("Invalid number");
} else {
  console.log(value + 5);
}

3. Using parseInt() for decimal values

Broken example:

let price = parseInt("19.99", 10);
console.log(price); // 19

Fix:

let price = parseFloat("19.99");
console.log(price); // 19.99

4. Forgetting the radix in parseInt()

Better practice:

let value = parseInt("42", 10);

Passing 10 makes your intent clear.

5. Assuming Number() and parseInt() behave the same

console.log(Number("123abc")); // NaN
console.log(parseInt("123abc", 10)); // 123

Choose the function based on whether partial parsing is acceptable.

Comparisons

MethodBest forInput must be fully numeric?Example inputResult
Number(value)General numeric conversionYes"123"123
+valueShort numeric conversionYes"123"123
parseInt(value, 10)IntegersNo"123abc"123
parseFloat(value)DecimalsNo"12.5px"12.5

Number() vs unary +

OptionAdvantageTrade-off
Number(value)Clear and readableSlightly longer
+valueShort and commonLess obvious to beginners

Which one should you use?

  • Use Number() for most beginner-friendly code
  • Use unary + if your team likes concise syntax
  • Use parseInt() when you want an integer specifically
  • Use parseFloat() when parsing decimal text that may include trailing characters
Take Quiz

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") -> 123
  • Number("12.5") -> 12.5
  • Number("123abc") -> NaN
  • +"123" -> 123
  • parseInt("123abc", 10) -> 123
  • parseFloat("12.5px") -> 12.5

Check for invalid conversion

const value = Number(input);
if (Number.isNaN(value)) {
  // handle invalid number
}

Good defaults

  • Prefer Number() for clarity
  • Use parseInt(..., 10) for integers
  • Use parseFloat() for decimals
  • Validate user input before using it

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

How do I convert a decimal string in TypeScript?

Use Number() or parseFloat().

const price = Number("19.99");

Should I use parseInt() with radix 10?

Yes. Writing parseInt(value, 10) is a good habit because it makes the base explicit.

Can I trust input from forms to already be a number?

No. Form input values are usually strings, even when they look numeric. Convert and validate them before using them.

Take Quiz

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 null when the input is not a valid number.
  • Demonstrate the function with integer, decimal, and invalid string inputs.
Take Quiz

Keep learning

Related questions

View more