Number() — the strict, predictable choice

console.log(Number("42"));     // 42
console.log(Number("3.14"));   // 3.14
console.log(Number("42px"));   // NaN

Number() converts the whole string or fails with NaN. That strictness is helpful when you want clean input only.

The unary plus shortcut

const value = +"99";
console.log(value);            // 99

A single + in front of a string is the most compact way to coerce it to a number, and it behaves exactly like Number().

parseInt() and parseFloat() for messy text

console.log(parseInt("42px", 10));   // 42
console.log(parseFloat("3.14rem"));  // 3.14

These read digits from the front and stop at the first non-numeric character. Always pass the radix 10 to parseInt so it never guesses the base.

Which method should you use?

  • Number() or + — when the string should be a clean number and anything else is an error.
  • parseInt() — when you need a whole number pulled from text like “42px”.
  • parseFloat() — when the value has a decimal point.

Frequently asked questions

Why do I keep getting NaN?

NaN means “not a number.” It appears when the string cannot be read as a number at all, such as Number("abc"). Check for it with Number.isNaN(value).

What is the difference between parseInt and Number?

parseInt reads digits until it hits a non-digit and returns what it found, while Number requires the entire string to be numeric or returns NaN.

Want to understand type coercion properly? Work through our free JavaScript course.