More JavaScript answers

by Danny
Published 2 min read

Use Number() for strict conversion, parseInt with a radix or parseFloat to read a number from the start of a string, and Number.isNaN to check the result is valid.

The short answer

#

Use Number(value) when the whole string should be a number. Use parseInt(value, 10) or parseFloat(value) when you want to read a number from the start of a string such as '12px'. Always check the result with Number.isNaN, because invalid input gives NaN rather than an error.


_10
const quantity = Number(input.value);
_10
_10
if (Number.isNaN(quantity)) {
_10
throw new Error('Please enter a number');
_10
}

Why it happens

#

Everything that comes from outside your code arrives as a string: form fields, URL parameters, localStorage, environment variables and command-line arguments. If you forget to convert, JavaScript's loose rules bite. + joins strings instead of adding, so '2' + 3 is '23'.

There are several ways to convert, and they disagree on edge cases:

InputNumber()parseInt(x, 10)parseFloat()
'42'424242
'3.14'3.1433.14
'12px'NaN1212
''0NaNNaN
' 7 '777
'0x1A'2600
'1e3'100011000

Number() is strict: the whole string, apart from surrounding whitespace, must be a valid number. parseInt and parseFloat read as far as they can and ignore the rest.

How to fix it

#

Number() for whole values

This is the best default for user input, because '12abc' becomes NaN instead of quietly turning into 12.


_10
Number('19.99'); // 19.99
_10
Number('19.99 GBP'); // NaN

Watch out for the empty string, which Number() turns into 0. Check for it first if empty should mean missing.


_10
function toNumber(text) {
_10
if (text.trim() === '') return null;
_10
const n = Number(text);
_10
return Number.isNaN(n) ? null : n;
_10
}

parseInt with a radix for integers

Pass the radix (the base) every time. 10 is what you want for everyday numbers.


_10
parseInt('42', 10); // 42
_10
parseInt('ff', 16); // 255
_10
parseInt('101', 2); // 5
_10
parseInt('12px', 10); // 12

Without a radix, a string starting with 0x is read as hexadecimal, which is rarely what you meant for user input.

parseFloat for decimals with trailing text


_10
const width = parseFloat(getComputedStyle(el).width); // '320.5px' becomes 320.5

Unary plus as a shorthand

+value does the same as Number(value). It is short, but easy to miss when reading code, so many teams prefer Number() for clarity.


_10
const total = +price + +shipping;

Check the result properly

Use Number.isNaN to detect failure and Number.isFinite to rule out Infinity as well. Number.isInteger checks for whole numbers.


_10
const n = Number(input);
_10
_10
Number.isNaN(n); // true only for NaN
_10
Number.isFinite(n); // false for NaN, Infinity and -Infinity
_10
Number.isInteger(n); // true for 5, false for 5.5

For form inputs, input.valueAsNumber on an input of type number gives you a number directly, or NaN when the field is empty or invalid.

Common pitfalls

#
  • Comparing with NaN. n === NaN is always false, because NaN is not equal to itself. Use Number.isNaN(n).
  • Using the global isNaN. isNaN('hello') converts first and returns true, which can confuse. Number.isNaN does no conversion.
  • Passing parseInt to map. ['1', '2', '3'].map(parseInt) gives [1, NaN, NaN], because map passes the index as the radix. Use .map(Number) or .map((s) => parseInt(s, 10)).
  • Using parseInt on numbers. parseInt(0.0000005) returns 5, because the number is first turned into the string '5e-7'. Use Math.trunc to drop decimals from a number.
  • Thousands separators. Number('1,000') is NaN. Strip separators first, and be aware that some locales use a comma as the decimal point.
  • Very large integers. Numbers above Number.MAX_SAFE_INTEGER lose precision. Use BigInt('9007199254740993') for large IDs, or keep them as strings.
#

Was this resource helpful?