Recommended Free Tools
Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
For a string that must represent a number from start to finish, use Number(value) (or unary +) and check the result. Use parseInt(value, 10) or parseFloat(value) only when accepting a valid numeric prefix is intentional: those parsers can ignore trailing text. The fifth option, multiplying by 1, also coerces a string but is usually less clear than Number().
These are JavaScript runtime behaviors, so TypeScript does not give the conversion functions different parsing rules. The important choice is whether you want full-string conversion or prefix parsing.
Choose the conversion that matches your input
Before choosing a method, decide what should happen when the input contains extra characters, is blank, or represents a number too large to handle exactly. These distinctions matter more than whether a method fits on one line.
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →- Require the entire string to be numeric: use
Number(value)or unary plus. - Accept an integer at the start of the string: use
parseInt(value, 10). - Accept a decimal number at the start of the string: use
parseFloat(value). - Prefer readable, explicit code: use
Number(value)for full conversion rather than multiplying by1.
For example, Number("12px") returns NaN, while parseInt("12px", 10) returns 12. The second result is useful only if accepting that prefix is actually what the program should do.
#1 Best Overall
1. Convert the whole string with Number()
Number(value) applies JavaScript number conversion to the whole string. It is a good default when trailing characters should make the input invalid.
const whole = Number("42"); // 42
const decimal = Number("3.14"); // 3.14
const withJunk = Number("42px"); // NaN
Leading and trailing whitespace is ignored. One important exception to keep in mind when processing form fields is that an empty or whitespace-only string converts to 0:
Number(""); // 0
Number(" "); // 0
If blank means “no answer” or “invalid” in your application, check for it before conversion. Number() also accepts hexadecimal, binary, and octal prefixes such as 0x, 0b, and 0o. Use it when that syntax is acceptable; validate separately if your input format must be narrower. See MDN’s Number reference.
A safe pattern for a decimal form field
function parseAmount(input: string): number | undefined {
if (input.trim() === "") return undefined;
const value = Number(input);
return Number.isNaN(value) ? undefined : value;
}
parseAmount("12.50"); // 12.5
parseAmount(" "); // undefined
parseAmount("12kg"); // undefined
This pattern rejects blank input and failed conversion. If the value must also be finite—for example, your application cannot accept positive or negative infinity—check Number.isFinite(value) as well.
Rank #2
- 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
2. Convert with unary plus
Unary plus is a compact way to request numeric coercion:
const whole = +"42"; // 42
const decimal = +"3.14"; // 3.14
const invalid = +"nope"; // NaN
For ordinary string inputs, its conversion behavior is broadly the same as Number(value), including turning an empty string into 0. It does not parse a valid prefix and discard the rest. Choose it when the concise syntax is familiar to the readers of your code; choose Number() when the explicit function call makes intent clearer. Unary plus throws if its operand is a BigInt, rather than converting that value to a number. See MDN’s unary plus reference.
3. Parse an integer prefix with parseInt()
parseInt(value, 10) reads an integer at the beginning of a string and stops when it reaches a character that is not valid for the chosen radix:
parseInt("12", 10); // 12
parseInt("12.9", 10); // 12
parseInt("12px", 10); // 12
parseInt("not a number", 10); // NaN
Pass radix 10 for ordinary decimal input. The radix tells the parser which number base to use; supply a different one only when that base is intentional. Because parseInt accepts prefixes, a successful result does not prove that the original string was a valid integer. For instance, parseInt("12.9", 10) gives 12, not an error. If decimals, suffixes, or other extra characters must be rejected, validate the whole input instead of relying on this function. See MDN’s parseInt reference and its grammar and types guide.
4. Parse a decimal prefix with parseFloat()
parseFloat(value) reads the longest valid decimal-number prefix, so it can return a number even if the string continues with other characters:
parseFloat("3.14"); // 3.14
parseFloat("3.14kg"); // 3.14
parseFloat("nope"); // NaN
This behavior is convenient when the application deliberately accepts a decimal followed by a suffix, but risky when the complete input must be valid. Validate the entire string separately if text after the number is not allowed. Do not use parseFloat to interpret hexadecimal notation: parseFloat("0x11") returns 0, not hexadecimal 17. See MDN’s parseFloat reference.
5. Coerce with multiplication by 1
Multiplying a numeric string by 1 invokes numeric coercion:
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
const value = "42" * 1; // 42
const invalid = "nope" * 1; // NaN
Like Number(), multiplication does not parse a numeric prefix and ignore the rest. For instance, "42px" * 1 produces NaN. This idiom is valid JavaScript, but it hides the conversion inside arithmetic and is generally less readable than Number(value). Use it only when its brevity genuinely helps; do not treat it as a separate parsing API. MDN’s guide to common conversion methods focuses on parseInt, parseFloat, Number, and unary plus, rather than recommending multiplication by one.
Compare the five methods
| Method | Behavior | Example | Watch out for |
|---|---|---|---|
Number(value) |
Converts the whole input | Number("12.5") → 12.5 |
Blank text becomes 0; trailing junk produces NaN |
+value |
Numeric coercion of the whole input | +"12.5" → 12.5 |
Blank text becomes 0; throws for a BigInt operand |
parseInt(value, 10) |
Parses an integer prefix in base 10 | parseInt("12.5", 10) → 12 |
Silently ignores trailing characters |
parseFloat(value) |
Parses a decimal prefix | parseFloat("12.5kg") → 12.5 |
Silently ignores trailing characters; does not parse hexadecimal |
value * 1 |
Numeric coercion through multiplication | "12.5" * 1 → 12.5 |
Less explicit than Number(); trailing junk produces NaN |
Check the result and validate the intended format
Use Number.isNaN() for failed conversion
When you convert a string with Number(), unary plus, or multiplication, check whether the result is NaN with Number.isNaN(value):
const value = Number("12oops");
if (Number.isNaN(value)) {
// Handle invalid numeric input.
}
The global isNaN() first coerces its argument, which can produce surprising answers when you pass it values that are not already numbers. Number.isNaN() checks specifically for the numeric NaN value without that coercion. See MDN’s isNaN reference.
Decide whether infinity and fractions are valid
A successful conversion is not necessarily a valid value for your application. If infinity is unacceptable, test with Number.isFinite(value). If the value must be a whole number, check that condition explicitly. If it must be an exactly represented integer, check the safe-integer range too.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Repair Windows errors before they cause bigger problems3Fix the driver behind crashes, sound loss and screen glitchesfunction parseSafeInteger(input: string): number | undefined {
if (input.trim() === "") return undefined;
const value = Number(input);
return Number.isSafeInteger(value) ? value : undefined;
}
This rejects decimal values, failed conversions, and integers outside JavaScript’s safe range. It also rejects strings that convert to a number but do not represent a whole number, rather than using parseInt to truncate them.
Best Value
Do not lose precision in large integers
JavaScript’s Number type uses IEEE 754 double-precision 64-bit binary floating point. Integer values are exactly represented only from −(253−1) through +(253−1), or −9,007,199,254,740,991 through +9,007,199,254,740,991. Outside that safe range, distinct integer values can collapse to the same number. For identifiers or other large integer text, preserve the string or use BigInt when integer arithmetic is required. See MDN’s references for numbers and strings and Number.
Common conversion problems and fixes
- Blank form input becomes zero: check
input.trim() === ""before callingNumber()or unary plus. - Text after a number is accepted: replace
parseIntorparseFloatwith full-string conversion if suffixes are not allowed. - A decimal is unexpectedly truncated:
parseIntreturns an integer prefix; useNumber()for a full decimal value. - An invalid result is not caught: use
Number.isNaN()on the converted value, or use an application-specific validation result. - A very large integer changes value: it may exceed the safe range for
Number; preserve the text or useBigIntfor integer work. - Input syntax is too permissive: conversion functions answer how JavaScript interprets a string, not whether it matches your product’s required format. Validate format and range as separate rules.
Or skip the browser setup
If your TypeScript project also needs website screenshots, ScreenshotNeo provides a screenshot API and MCP server; it is separate from string-to-number conversion. A single GET request can return an image or PDF. For example, using the API from Node.js:
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
See the ScreenshotNeo documentation for API details. Before capture, it accepts cookie or consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed. Its MCP server includes tools for AI agents to take screenshots. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Sign up for ScreenshotNeo’s free plan.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Frequently Asked Questions
Does TypeScript change how these string conversions work?
No. These conversion rules are JavaScript runtime behavior; TypeScript adds static types but does not change the parsing semantics.
Can parseInt be used to check that a string contains only an integer?
No. It can return an integer from a valid prefix while ignoring later characters, so use full-string validation when extra text must be rejected.
Quick Recap
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.

