JavaScript Medium technical 1 views 1 min read

How do you convert a string to a number in JavaScript?

Peer-reviewed by HireXTech Technical Panel Updated for 2025/2026 hiring Editorial standards
Practise this track
Interviewer Expectations for this Question
01
Core Competency

Assesses fundamental understanding of JavaScript conventions, runtime behavior, and memory/performance considerations.

02
Evaluation Criteria

Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.

Comprehensive Model Answer Verified Solution

In JavaScript, there are several methods to convert a string representation of a number into an actual numeric type, each with distinct edge case behaviors:

### 1. Number(str) Function (Recommended for Exact Numbers)
Parses the entire string as a number. Returns NaN if the string contains any non-numeric characters (except leading/trailing whitespace):

Number("42");     // 42
Number("42.5");   // 42.5
Number("42px");   // NaN (strict parsing)
Number("");       // 0

### 2. Unary Plus Operator (+str)
The fastest syntax, behaves identically to Number(str):

+"123.45"; // 123.45
+"abc";    // NaN

### 3. parseInt(str, radix)
Parses characters from left to right until encountering an invalid character. Always provide radix 10 to prevent legacy octal misinterpretations:

parseInt("42px", 10);    // 42
parseInt("010", 10);     // 10
parseInt("abc", 10);     // NaN

### 4. parseFloat(str)
Parses floating-point decimals from left to right:

parseFloat("3.14159rad"); // 3.14159

### Comparison Summary:
Use Number() or + when validating clean numbers where trailing letters indicate an invalid input; use parseInt() or parseFloat() when parsing CSS values like "16px" or "2.5rem".

Candidate Response Strategy & Interview Tips

  1. Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
  2. Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
  3. Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
  4. Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.
Related Topics & Skills
Spotted an error or have an alternative solution?