How to convert strings to numbers in JavaScript

· Category: JavaScript

Short answer

Use Number() for strict conversion, parseInt() and parseFloat() for partial parsing, and the unary plus (+) for concise coercion when the string is clean.

Steps

  1. Use Number() for strict numeric conversion: javascript Number('42'); // 42 Number('42px'); // NaN
  2. Use parseInt() to extract integers from mixed strings: javascript parseInt('42px', 10); // 42 parseInt('101', 2); // 5
  3. Use parseFloat() for decimal extraction: javascript parseFloat('3.14em'); // 3.14
  4. Use unary plus for brevity: javascript +'42'; // 42

Tips

  • Always pass the radix (10) to parseInt() to avoid octal interpretation in older environments.
  • Number('') is 0, while Number(' ') is also 0; handle empty inputs explicitly.

Common issues

  • parseInt(null) returns NaN, but Number(null) returns 0.
  • Large integers parsed from strings may lose precision past Number.MAX_SAFE_INTEGER.