Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk3 min

How to Convert a String to a Number in TypeScript

Use Number() for whole-value conversion, parseInt() or parseFloat() for intentional prefixes, and BigInt for large integers that must stay exact.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Number(text) when the entire input should represent a number. Use parseInt(text, 10) or parseFloat(text) only when you deliberately want to read an integer or decimal prefix. TypeScript does not convert a string just because you annotate or assert it as a number; conversion happens at runtime using JavaScript.

Choose the conversion method that matches your input

What you need Use Behavior
Convert the whole string to a number Number(text) Use when trailing nonnumeric text should not be accepted as part of a value. Check for NaN afterward.
The same general conversion in a compact expression +text Unary plus explicitly coerces the value to a number. Number(text) is often easier to read, especially in beginner code.
Read an integer prefix parseInt(text, 10) Reads an integer from the start; it can ignore trailing text and drops a fractional part. Specify radix 10 for ordinary decimal input.
Read a decimal prefix parseFloat(text) Reads a decimal or exponent prefix and can ignore trailing text.
Keep an integer larger than Number can represent precisely BigInt(text) Converts an integer string to a BigInt without first rounding it through Number.

Convert a whole value with Number()

For input that is supposed to consist entirely of a numeric value, use Number():

As an Amazon Associate I earn from qualifying purchases.

const value = Number("42");

Unary plus has the same general coercion intent when you want a shorter expression:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

const value = +"42";

Choose this whole-value approach rather than prefix parsing when a suffix such as px should make the input invalid. The conversion can return NaN, so check its result when input may be invalid or user-supplied.

Use parseInt() and parseFloat() only for prefixes

The parsing functions accept a valid numeric prefix rather than requiring the entire string to be numeric. That can be useful for extracting a value from a larger string, but it is not strict validation of a field.

Integer prefixes

Pass radix 10 for ordinary decimal integer input:

const pixels = parseInt("42px", 10); // 42

parseInt("1.9", 10) returns 1, and parseInt("123_456", 10) returns 123. These results illustrate why a successful parse does not prove the whole input meets a field’s requirements.

Rank #2
TypeScript Programming Language - Software Engineer & Coder T-Shirt
  • TypeScript implements a superset of syntax for strictly typed development, facilitating deep static analysis and enhanced development environment integration. The compiler translates source into standard script formats, ensuring parity across any runtime.
  • TypeScript is ideal for front-end developers, full-stack engineers, and software architects who build large-scale web applications. It serves those looking to improve code excellence, reduce bugs through static checking, and maintain complex projects more.
  • Lightweight, Classic fit, Double-needle sleeve and bottom hem

Decimal prefixes

parseFloat() reads a decimal or exponent prefix:

const amount = parseFloat("3.14kg"); // 3.14

That behavior may suit extraction from a string containing a unit. If the entire field must be a valid numeric value, use a whole-value conversion and validate according to the input format you accept.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Check for NaN without rejecting zero

When conversion fails, the result may be NaN. Use Number.isNaN() to detect that result; do not use a truthiness check, because 0 is a valid numeric result.

const parsed = Number(userInput);
if (Number.isNaN(parsed)) {
  throw new Error("Expected a numeric value");
}

For stricter validation, define which forms your application accepts and validate the whole input against that rule. Prefix parsers alone cannot tell you whether unexpected trailing characters should be allowed.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

TypeScript types do not convert values at runtime

TypeScript adds static checking to JavaScript, while string and number describe primitive values. An assertion such as text as number only changes how the compiler views an expression; it does not turn the underlying string into a number. Use a runtime conversion such as Number(text) instead. See the TypeScript Handbook’s Everyday Types and TypeScript for JavaScript Programmers.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

TypeScript 5.0 release notes show unary plus as an explicit coercion before a comparison and document compiler diagnostics for potentially implicit string-to-number coercion in relational comparisons. That compiler behavior does not make type assertions perform conversions. TypeScript 5.0 Release Notes.

Use BigInt for very large integer strings

JavaScript’s ordinary Number type uses floating-point representation, so integers outside its precise range can lose integer precision. For a large integer that must remain exact, convert directly to BigInt rather than passing through Number or relying on parseInt.

const id = BigInt("900719925474099267");

MDN demonstrates that parsing "900719925474099267n" with parseInt() produces a rounded value and recommends BigInt("900719925474099267") for the intended BigInt value. MDN: parseInt(). For ordinary integer and decimal prefix behavior, see MDN: parseFloat().

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

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

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.