Convert String to Number in JavaScript
Master reliable ways to convert strings to numbers in JavaScript, including Number(), unary plus, parseInt, and parseFloat, with validation and edge-case handling for robust code.
To convert a string to a number in JavaScript, choose a method based on the input. Use Number(value) or the unary plus operator for clean coercion when you expect numeric strings, parseInt/parseFloat for mixed content, and always validate with Number.isNaN to guard against NaN results. This covers convert string to number javascript reliably.
Why converting strings to numbers matters in JavaScript
Strings arrive from forms, URLs, APIs, and local storage, and most downstream logic expects numeric data. Misconverting can lead to incorrect calculations, broken validations, and subtle bugs that slip past tests. In this guide, we explore how to convert string to number javascript safely and predictably, using the right tool for each scenario. By understanding the strengths and pitfalls of Number(), the unary plus, and parsing functions like parseInt and parseFloat, you’ll write more robust code. You’ll also learn when to validate results and how to avoid common coercion traps that can surprise even experienced developers.
// method 1: Number(...)
const a = "42";
const b = Number(a);
console.log(b, typeof b); // 42 "number"// method 2: unary plus
const s = "42";
const t = +s;
console.log(t, typeof t); // 42 "number"// method 3: parseInt for strings with trailing text
const w = "42px";
const v = parseInt(w, 10);
console.log(v); // 42- Important note: Number("") evaluates to 0, while Number(undefined) evaluates to NaN. This distinction matters when validating user input or optional fields. Understanding these rules helps you design safer defaults and clearer error handling.
wordCountNoteIncludedInBlock
Steps
Estimated time: 60-90 minutes
- 1
Identify numeric input sources
Scan your codebase for strings that are used as numbers (e.g., user input, query params). Decide expected formats and edge cases. This helps you pick the right conversion method and validation strategy.
Tip: Log inputs during development to verify their type before conversion. - 2
Choose a conversion strategy
Pick Number(), unary plus, parseInt, or parseFloat depending on whether you need integers, decimals, or a permissive parse of mixed content.
Tip: Prefer explicit parsing (parseInt/parseFloat) when dealing with mixed content. - 3
Implement conversion with validation
Convert and check with Number.isNaN to guard against invalid strings. Consider returning null or a default instead of propagating NaN.
Tip: Return a sentinel value or null on NaN to avoid runtime errors. - 4
Test with representative inputs
Create unit tests for valid numbers, decimals, empty strings, and non-numeric input. Include edge cases like '0', '0.0', '', 'abc', and '12px'.
Tip: Automate tests to catch regressions in conversion logic. - 5
Integrate into production code
Standardize a conversion helper across modules to ensure consistent behavior and privacy of NaN handling.
Tip: Document your chosen strategy in a coding standards page. - 6
Monitor and refine
Review conversion results in logs and adjust handling of NaN or Infinity as needed. Refine your helper based on real input.
Tip: Consider returning null instead of NaN to simplify downstream logic.
Prerequisites
Required
- Required
- Modern browser dev tools or a Node.js environmentRequired
- Basic knowledge of JavaScript types and Number APIRequired
- Access to a console or terminalRequired
Optional
- A code editor (e.g., VS Code)Optional
- Optional TypeScript basicsOptional
Keyboard Shortcuts
| Action | Shortcut |
|---|---|
| CopyCode blocks or editor | Ctrl+C |
| PasteCode blocks or editor | Ctrl+V |
| Format documentIn VS Code or IDE | ⇧+Alt+F |
| SaveAny file | Ctrl+S |
Questions & Answers
What is the difference between Number(), parseInt(), and parseFloat()?
Number() converts the entire string to a number and returns NaN on failure. parseInt() parses an integer with an optional radix, stopping at first non-digit. parseFloat() parses a decimal number. Use the right tool for your input.
Number(), parseInt(), and parseFloat() are different ways to turn strings into numbers; pick based on whether you need integers or decimals.
Why does 'abc' become NaN with Number('abc')?
Non-numeric strings cannot be parsed as numbers, so the conversion yields NaN. Always check with Number.isNaN after conversion.
If your string isn’t numeric, conversion yields NaN; validate before using the value.
Is '' treated as 0 when converting?
Yes, Number('') returns 0. This can cause silent data loss if your input is empty. Validate inputs before conversion.
An empty string becomes zero when converted, which might surprise users.
Can I use parseInt without a radix?
Always specify a radix, e.g., parseInt('08', 10), to avoid differences across environments. Without a radix, behavior may be inconsistent.
Always tell parseInt the base, like 10, to avoid surprises.
What about converting numbers from JSON?
JSON numeric values are already numbers; strings that contain numbers may need conversion before arithmetic. Use Number() or + to convert if needed.
JSON values that are strings with digits can be turned into numbers with Number or +.
How should I handle invalid conversions?
Define a clear policy: return null or a default value when conversion fails. Propagate errors if necessary for robust apps.
If conversion fails, return a safe value instead of NaN to keep downstream logic simple.
What to Remember
- Use Number(value) or +value for clean numeric conversion
- ParseInt/parseFloat support decimals and bases; specify radix
- Always validate with Number.isNaN to detect invalid input
- Choose a helper function to standardize behavior across code
