Converting JavaScript Strings to Numbers: A Practical Guide

Learn reliable techniques to convert JavaScript strings to numbers using Number(), parseInt(), parseFloat(), and the unary plus operator, with robust edge-case handling and best practices for avoiding NaN and subtle bugs.

JavaScripting
JavaScripting Team
·5 min read
String to Number Guide - JavaScripting
Quick AnswerDefinition

In JavaScript, strings can be converted to numbers using Number(), parseInt(), parseFloat(), or the unary plus operator. Each approach handles whitespace, prefixes, and non-numeric suffixes differently, and can yield NaN for non-numeric input. This guide covers when to use each method and how to avoid common conversion mistakes.

Understanding the problem

In JavaScript, numbers are primitive values while strings are sequences of characters. When your program reads user input or parses data from APIs, you often need to turn a string into a number to perform arithmetic or comparisons. The built-in tools for this task are Number(), parseInt(), parseFloat(), and the unary plus operator. Each has different rules for whitespace, prefixes, and non-numeric suffixes, so choosing the right one matters.

JavaScript
Number("42") // 42 Number(" 42 ") // 42 Number("") // 0 Number("42px") // NaN

parseInt and parseFloat parse as much as they can from the start of the string, then stop. They also accept a radix for parseInt, which is essential to avoid surprises. The unary plus is a compact shorthand that often mirrors Number(), but it follows the same rules as Number().

description_text_counted_if_needed":null},

Core conversion functions: when to pick what

The primary tools are: Number(), parseInt(), parseFloat(), and the unary + operator. Use Number() when you want a strict conversion from strings that should represent a numeric value. Use parseInt() with a radix of 10 to avoid octal interpretation and focus on integer parts. Use parseFloat() for decimals and + as a concise shorthand when you know the input is clean. Examples below demonstrate typical usage.

JavaScript
Number("123") // 123 Number(" 123 ") // 123 parseInt("123", 10) // 123 parseInt("012", 10) // 12 parseFloat("3.14") // 3.14 +"56" // 56 +"56.7" // 56.7

Note how whitespace is preserved in the input and how radix affects parseInt results. The unary plus behaves like Number() and adheres to its rules.

description_text_counted_if_needed":null},

Handling edge cases and avoiding NaN

Edge cases are where many mistakes happen. Strings like "", " ", or "abc" each yield specific results that can surprise you if you assume a numeric outcome. Use Number.isNaN() to reliably detect NaN values instead of the global isNaN function, which can be misleading for non-numeric strings. The following snippet shows typical patterns and their outputs:

JavaScript
Number("") // 0 Number(" ") // 0 Number("abc") // NaN Number.isNaN(Number("abc")) // true

To guard against NaN in practical code, convert and then check, returning a safe default or signaling an error when appropriate. This approach helps avoid silent logic bugs when numeric input is expected.

description_text_counted_if_needed":null},

Real-world patterns and examples

Strings often come from user input or external data and may contain non-numeric characters. A common pattern is to strip non-numeric suffixes before conversion. For example, turning "$9.99" into a numeric value for calculations:

JavaScript
const priceLabel = "price: $9.99"; const amount = parseFloat(priceLabel.replace(/[^0-9.]/g, "")); // 9.99

Another real-world case is extracting integers from mixed strings like "version 2.0":

JavaScript
parseInt("version 2.0", 10) // NaN Number("2.0") // 2

When you expect a decimal, prefer parseFloat or the unary plus on a trimmed string. If you expect strict numeric input, use Number() and guard for NaN.

description_text_counted_if_needed":null},

Best practices and pitfalls

To build robust conversions, follow these patterns:

  • Always trim input before conversion: str.trim()
  • Prefer Number() or unary + for clear intent, and use Number.isNaN() to check for invalid numeric results
  • Use parseInt with an explicit radix (10) to avoid surprises from legacy or octal interpretations
  • Avoid implicit coercion in arithmetic expressions; it hides failure modes
JavaScript
function toNumberSafe(s) { if (typeof s !== "string") s = String(s); const trimmed = s.trim(); const n = Number(trimmed); return Number.isNaN(n) ? null : n; }

This approach reduces hidden bugs and makes the conversion behavior explicit in your codebase.

description_text_counted_if_needed":null}],

prerequisites":{"items":[{

item

required

true

link

Steps

Estimated time: 20-30 minutes

  1. 1

    Identify input string

    Determine the source of the string and whether it should represent an integer or a floating-point value. Decide whether you expect prefixes or non-numeric suffixes to be present.

    Tip: Ask: does the string come from user input or a data source?
  2. 2

    Choose conversion function

    If the input should be a whole number, consider parseInt with radix 10 or Number(). For decimals, use parseFloat or Number().

    Tip: Prefer explicit function calls over implicit coercion.
  3. 3

    Trim and sanitize

    Remove leading/trailing whitespace and optional non-numeric characters that could break parsing. This prevents subtle NaN results.

    Tip: Use .trim() and a regex to sanitize when needed.
  4. 4

    Convert and verify

    Perform the conversion and then verify the result with Number.isNaN() to handle invalid inputs gracefully.

    Tip: Avoid relying on NaN equality—always check with Number.isNaN.
  5. 5

    Handle edge cases

    Decide on a fallback for invalid inputs (e.g., null, undefined, or NaN) and document it for maintainers.

    Tip: Return a sentinel value or throw a clear error.
  6. 6

    Test with representative samples

    Test the function across typical inputs: integers, decimals, empty strings, whitespace, and invalid strings.

    Tip: Include boundary cases like "", " ", "abc", "42px".
Pro Tip: Prefer explicit conversions (Number(), parseInt/parseFloat) over implicit coercion for readability.
Warning: NaN propagates through arithmetic. Use Number.isNaN to detect invalid results.
Note: Always specify radix 10 in parseInt to avoid surprises in some environments.
Pro Tip: Trim input before conversion to reduce edge-case failures.

Prerequisites

Required

Optional

  • Regex basics for data cleaning
    Optional

Commands

ActionCommand
Check conversion in Node.jsQuick test of a simple numeric stringnode -e 'console.log(Number("123"))'
Parse integer with radixDemonstrates radix usage with mixed inputnode -e 'console.log(parseInt("42px", 10))'
Parse float from stringExtracts decimal part from stringnode -e 'console.log(parseFloat("3.14 is pi"))'

Questions & Answers

What is the difference between Number(), parseInt(), and parseFloat()?

Number() performs a strict conversion and returns NaN if the string is not a valid number. parseInt() extracts an integer from the start of a string with an optional radix and may ignore trailing non-numeric characters. parseFloat() parses a floating-point number from the start of the string. Unary + is a shorthand for Number().

Number() is strict and returns NaN on invalid input; parseInt() and parseFloat() parse from the start of the string, with parseInt requiring a radix and potentially ignoring decimals.

How do I safely convert a string to a number in JavaScript?

Trim the string, choose the appropriate converter (Number or +), then check the result with Number.isNaN(). If the result is NaN, provide a fallback value or throw a controlled error. This minimizes runtime surprises and improves reliability.

Trim and convert, then check for NaN to handle bad input gracefully.

What happens with non-numeric suffixes like '42px'?

parseInt('42px', 10) yields 42 because it stops at the first non-digit character. Number('42px') and +'42px' return NaN because the entire string must be a valid number. For decimals, use parseFloat if the numeric part is followed by text.

If there's text after the number, parseInt may still grab the number, but Number and + will fail.

Is there a difference between unary plus and Number()?

They behave the same for most inputs; both apply the same parsing rules. The unary plus is just a shorter syntax. Use whichever enhances readability in your codebase.

They’re equivalent in behavior; the plus sign is just a shorter way to call Number().

Why should I specify a radix in parseInt?

Without a radix, parseInt may interpret strings in an unexpected base depending on environment. Always use a radix of 10 when parsing decimal numbers from strings.

Always pass 10 as the radix to get predictable decimal parsing.

What should I return if conversion fails?

Return a sentinel value like null or NaN depending on your error-handling strategy, or throw a descriptive error. Document the behavior so callers know how to handle failures.

Return null or throw a clear error to signal conversion failure.

What to Remember

  • Convert strings with clear intent using Number() or unary +.
  • Use parseInt with radix 10 for integers from mixed strings.
  • Guard results with Number.isNaN to detect invalid conversions.
  • Sanitize input (trim, strip non-numeric chars) before parsing when needed.

Related Articles