Ship internal tools in hours, not weeks. Real auth, users, jobs, audit logs, and cohesive UI included. Early access $249 $499 → [Get it now]

How to convert a string to a number in JavaScript

Converting strings to numbers is essential for form data processing, mathematical calculations, and API data handling in JavaScript applications. With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented string-to-number conversion extensively in input fields, calculators, and data processors. The most robust and recommended approach is the Number() constructor, which provides consistent conversion behavior and clear error handling. Always validate the result with Number.isNaN() when handling user input.

Use the Number() constructor to convert a string to a number.

Number('42')     // 42
Number('3.14')   // 3.14
Number('')       // 0
Number('hello')  // NaN

Number() converts the entire string. Non-numeric content returns NaN; empty strings and whitespace-only strings return 0.

1. Number() Constructor

Number() is the most explicit and predictable method. It handles integers, decimals, scientific notation, and hex strings.

Number('42')        // 42
Number('3.14')      // 3.14
Number('1e3')       // 1000
Number('0xff')      // 255
Number('  10  ')    // 10  — trims whitespace
Number('')          // 0
Number('123px')     // NaN — non-numeric suffix fails entirely
Number(null)        // 0
Number(undefined)   // NaN
Number(true)        // 1
Number(false)       // 0

The key characteristic: the entire string must be numeric (after trimming). A single non-numeric character causes the whole conversion to fail with NaN.

2. parseInt()

parseInt() parses from the left and stops at the first non-numeric character. It only produces integers (decimal part is dropped, not rounded).

parseInt('42')       // 42
parseInt('3.99')     // 3   — decimal truncated
parseInt('123px')    // 123 — stops at 'p'
parseInt('px123')    // NaN — starts with non-numeric
parseInt('10', 2)    // 2   — binary parsing via radix
parseInt('ff', 16)   // 255 — hex parsing
parseInt('')         // NaN

Always pass the radix (second argument) when parsing non-decimal strings to avoid subtle bugs in older environments.

Key difference from Number(): parseInt('123px') returns 123 while Number('123px') returns NaN. Use parseInt when the string may have a unit suffix (e.g. CSS values like '16px').

3. parseFloat()

parseFloat() works like parseInt() but preserves the decimal portion. It has no radix parameter.

parseFloat('3.14')      // 3.14
parseFloat('3.14abc')   // 3.14 — stops at 'a'
parseFloat('1e3')       // 1000
parseFloat('.5')        // 0.5
parseFloat('')          // NaN
parseFloat('px3.14')    // NaN — starts with non-numeric

Use parseFloat() when working with decimal values that may have trailing units, such as values read from CSS or measurement strings.

4. Unary Plus Operator

The unary + is a concise shorthand for Number(). It behaves identically but is less readable for developers unfamiliar with the pattern.

+'42'       // 42
+'3.14'     // 3.14
+''         // 0
+'hello'    // NaN
+true       // 1
+null       // 0
+undefined  // NaN

Reserve the unary + for internal utility code where brevity matters. In application code or shared libraries, prefer the explicit Number() for clarity.

5. Validating the Result

Any conversion from user input should be validated before use. An invalid input produces NaN, which silently corrupts downstream calculations.

function toNumber(value) {
  const n = Number(value)
  if (Number.isNaN(n)) {
    throw new Error(`Cannot convert "${value}" to a number`)
  }
  return n
}

toNumber('42')      // 42
toNumber('hello')   // throws Error

For form inputs, you may want to return null instead of throwing:

function parseInput(inputElement) {
  const value = inputElement.value.trim()
  if (value === '') return null
  const n = Number(value)
  return Number.isNaN(n) ? null : n
}

See the CoreUI form validation docs for combining this with visual error feedback. Also check how to check if a string is empty in JavaScript before converting, since Number('') returns 0 which may not be what you want.

6. Choosing the Right Method

Method Decimal Trailing units Empty string Recommended for
Number() yes NaN 0 General conversion
parseInt() no (truncates) parses NaN Integer extraction, CSS units
parseFloat() yes parses NaN Decimal extraction, CSS units
Unary + yes NaN 0 Concise internal utilities

When in doubt, use Number() and validate with Number.isNaN().

Best Practice Note:

We use Number() paired with Number.isNaN() validation throughout CoreUI’s JavaScript utilities for processing form inputs, API responses, and configuration values. Always be explicit about your intent: if you need an integer, use parseInt() with a radix; if you need a decimal, use parseFloat() or Number(). Never rely on implicit type coercion (value * 1 or value - 0) in shared or production code — it obscures intent and surprises future readers.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author