How to Convert a String to a Number in JavaScript

By Marko Denic
Contents
  1. Number() vs parseInt() vs parseFloat() vs +
  2. Number(): the strict choice
  3. parseInt(): whole numbers from the start of a string
  4. parseFloat(): decimals from the start of a string
  5. Unary plus: the short version of Number()
  6. Validate the result
  7. Thousands separators and other locales
  8. Big integers: use BigInt
  9. Money and decimals
  10. Where strings come from
  11. FAQ

Short answer: use Number(str). It converts the whole string, and returns NaN if any part of it isn’t a number. Use parseInt(str, 10) or parseFloat(str) when the string starts with a number you want to pull out, like "42px".

The methods behave very differently on empty strings, spaces, units and hex. Here’s how each one works, a table of the cases that trip people up, and how to convert safely.

Number() vs parseInt() vs parseFloat() vs +

Input Number(x) parseInt(x, 10) parseFloat(x) +x
"42" 42 42 42 42
"42.9" 42.9 42 42.9 42.9
"42px" NaN 42 42 NaN
" 42 " 42 42 42 42
"" 0 NaN NaN 0
"1e3" 1000 1 1000 1000
"0x1F" 31 0 0 31
"1,000" NaN 1 1 NaN
"abc" NaN NaN NaN NaN
null 0 NaN NaN 0

The bold cells are the classic bugs: an empty form field silently becomes 0, and parseInt stops at the first character it doesn’t understand, so "1,000" becomes 1.

Number(): the strict choice

Number() trims whitespace, then converts the whole string or returns NaN. It understands decimals, exponents ("1e3"), and hex, binary and octal prefixes ("0x1F", "0b101", "0o17"). The one surprise: an empty or whitespace-only string becomes 0.

javascript
Number('42');      // 42
Number('3.14');    // 3.14
Number(' 42 ');    // 42
Number('42px');    // NaN
Number('');        // 0  ← careful
Number('1e3');     // 1000
Number('0x1F');    // 31
Number('12_000');  // NaN (numeric separators only work in code)

parseInt(): whole numbers from the start of a string

parseInt() reads digits from the start of the string and stops at the first character that doesn’t fit, so it’s the one to use for values with units. It drops decimals instead of rounding. Always pass the radix (10 for decimal) so there’s no doubt how the string is read.

Never pass parseInt straight to map(): map passes the index as the second argument, which becomes the radix. Use map(Number) instead.

javascript
parseInt('42px', 10);   // 42
parseInt('42.9', 10);   // 42 (truncated, not rounded)
parseInt('px42', 10);   // NaN (must start with the number)
parseInt('ff', 16);     // 255
parseInt('101', 2);     // 5

['1', '2', '3'].map(parseInt);  // [1, NaN, NaN] ← radix bug
['1', '2', '3'].map(Number);    // [1, 2, 3]

parseFloat(): decimals from the start of a string

parseFloat() works like parseInt() but keeps the decimal part and understands exponents. It always reads base 10 and doesn’t take a radix, so hex strings come out as 0.

javascript
parseFloat('3.14abc'); // 3.14
parseFloat('1.5rem');  // 1.5
parseFloat('1e3');     // 1000
parseFloat('.5');      // 0.5
parseFloat('0x1F');    // 0

Unary plus: the short version of Number()

A + in front of a value converts it exactly like Number() does, including the empty-string-to-0 behavior. It’s short, but easy to miss when reading code, so many teams prefer the explicit Number(). It also explains a common bug: + between two strings joins them instead of adding.

javascript
+'42';        // 42
+'';          // 0

'3' + '4';    // '34' (string concatenation)
+'3' + +'4';  // 7
'5' - 3;      // 2 (- always converts to numbers)

Validate the result

Every method returns NaN on failure, and NaN is a number (typeof NaN === 'number') that isn’t equal to anything, itself included. Check it with Number.isNaN() or, better, Number.isFinite(), which also rejects Infinity. Avoid the global isNaN(): it converts its argument first, so isNaN('') is false.

This helper handles the empty-string trap too:

javascript
function toNumber(value) {
  if (typeof value !== 'string' || value.trim() === '') return null;
  const number = Number(value);
  return Number.isFinite(number) ? number : null;
}

toNumber('42');      // 42
toNumber('');        // null (not 0)
toNumber('42px');    // null
toNumber('Infinity'); // null

Thousands separators and other locales

JavaScript only understands a . as the decimal point and no grouping separators. A user typing 1,234.56 (US) or 1.234,56 (Germany) needs cleaning up first. Use <input type="number"> where you can, so the browser handles the user’s locale for you.

javascript
Number('1,234.56');                     // NaN
Number('1,234.56'.replaceAll(',', ''));  // 1234.56

// German format: drop the dots, swap the comma for a dot
Number('1.234,56'.replaceAll('.', '').replace(',', '.')); // 1234.56

Big integers: use BigInt

A JavaScript number can only represent integers exactly up to Number.MAX_SAFE_INTEGER (9,007,199,254,740,991). Larger IDs from an API or database silently lose precision. Convert them with BigInt(), or keep them as strings if you only display them.

javascript
Number('9007199254740993');  // 9007199254740992 ← wrong, silently
BigInt('9007199254740993');  // 9007199254740993n

Number.isSafeInteger(Number('9007199254740993')); // false

Money and decimals

Converting is exact, but decimal math isn’t: 0.1 + 0.2 is 0.30000000000000004. toFixed() rounds for display, and it returns a string, so wrap it in Number() if you need to keep calculating. For money, the safest approach is to work in cents as integers.

javascript
Number('0.1') + Number('0.2');  // 0.30000000000000004
(0.1 + 0.2).toFixed(2);          // '0.30' (a string)
Number((0.1 + 0.2).toFixed(2));  // 0.3

// Work in cents
const cents = Math.round(Number('19.99') * 100); // 1999

Where strings come from

Most “my numbers won’t add up” bugs start with a value that looks like a number but is a string: To see how JavaScript converts types on its own, try this JavaScript type coercion quiz.

  • Form inputs. input.value is always a string, even for <input type="number">. Number inputs also have input.valueAsNumber, which returns a real number (or NaN when the field is empty). More on the input types in HTML input types.
  • URL query parameters. params.get('page') returns "2", not 2. See URLSearchParams.
  • localStorage and cookies store strings only.
  • data attributes. element.dataset.count is a string.
  • CSV files and some APIs send numbers as text.

Convert at the edge, right where the value enters your code, and the rest of your code can trust it’s a number. For more small but useful patterns, see these JavaScript tips.

FAQ

What’s the best way to convert a string to a number in JavaScript?

Number(str) for most cases, because it fails loudly with NaN instead of returning part of the string. Check the result with Number.isFinite(), and handle empty strings separately.

How do I convert a string to an integer?

parseInt(str, 10) if the string can contain extra text after the number. If it must be a clean number, use Math.trunc(Number(str)), or Math.round() to round instead of cutting off the decimals.

How do I convert an array of strings to numbers?

array.map(Number). Don’t use array.map(parseInt): the index becomes the radix and you get NaN from the second item on.

Which method is fastest?

The difference is a few nanoseconds per call and won’t show up in a real app. Pick the one whose behavior you want, and the one your team can read.

How do I convert a number back to a string?

String(num), num.toString() or a template literal: `${num}`. Use num.toFixed(2) for a fixed number of decimals.