How do you convert a string to a number in JavaScript?

JavaScript

The short answer

The most common ways are Number(), parseInt(), parseFloat(), and the unary + operator. Each behaves slightly differently with edge cases like empty strings, whitespace, and non-numeric characters.

The methods

// Number() — strict conversion
Number('42'); // 42
Number('3.14'); // 3.14
Number(''); // 0
Number('hello'); // NaN
Number('42px'); // NaN — does not ignore trailing text
// parseInt() — parses integers, ignores trailing text
parseInt('42'); // 42
parseInt('42px'); // 42 — stops at non-numeric character
parseInt('3.14'); // 3 — drops the decimal
parseInt('0xFF', 16); // 255 — supports different bases
// parseFloat() — parses decimals, ignores trailing text
parseFloat('3.14'); // 3.14
parseFloat('42px'); // 42
parseFloat('3.14.15'); // 3.14 — stops at second dot
// Unary + operator — same as Number()
+'42'; // 42
+'3.14'; // 3.14
+''; // 0
+'hello'; // NaN

Which one to use

  • Number() — when you want strict conversion (reject anything that is not purely a number)
  • parseInt() — when you need an integer and want to ignore trailing text (like '42px')
  • parseFloat() — when you need a decimal and want to ignore trailing text
  • + operator — shorthand for Number(), common in one-liners

Common gotchas

Number(null); // 0
Number(undefined); // NaN
Number(true); // 1
Number(false); // 0
Number([]); // 0
Number([1]); // 1
Number([1, 2]); // NaN
parseInt(''); // NaN (but Number('') is 0)
parseInt('0x1F'); // 31 — parses as hex automatically

Always check for NaN after conversion:

const num = Number(userInput);
if (Number.isNaN(num)) {
console.log('Not a valid number');
}

Use Number.isNaN(), not the global isNaN(). The global isNaN('hello') returns true because it coerces the string first, while Number.isNaN('hello') returns false (it only returns true for actual NaN values).

Interview Tip

Show Number(), parseInt(), and parseFloat() with the same inputs to highlight the differences. The '42px' example is the clearest differentiator — Number returns NaN, parseInt returns 42. Mentioning Number.isNaN vs isNaN is a good bonus.

Why interviewers ask this

This tests basic JavaScript knowledge about type conversion. Interviewers want to see if you know the different methods and their edge cases, especially the difference between Number() and parseInt().