Converting a string to a number in JavaScript is surprisingly subtle. With NaN
, implicit radixes, and numbers vs Numbers, there are a lot of ways to shoot yourself in the foot. In this article, I’ll cover the tradeoffs of parseFloat()
vs Number()
and Number.isNaN()
vs isNaN()
. I’ll also describe how to enforce these rules with eslint.
The TLDR is you should use [Number(x)
] to convert generic JavaScript values to numbers if you want to be permissive, or parseFloat(x)
if you want to be more strict. You should always use Number.isNaN()
to check if the conversion failed. You should not use the global isNaN()
function.
typeof parseFloat('42'); // 'number'
Number.isNaN(Number('42')); // false
typeof parseFloat('fail'); // 'number'
Number.isNaN(Number('fail')); // true
Using Number(x)
has several edge cases that may be correct depending on your perspective. You can also use a tool like archetype that handles some of these edge cases for you:
archetype.to('42', 'number'); // 42
Number(''); // 0
archetype.to('', 'number'); // throws
Many developers use +x
to convert a string to a number. The JavaScript language spec states that +x
is equivalent to Number(x)
.
+'42 fail'; // NaN
+({ valueOf: () => '42' }); // 42
+({ toString: () => '42' }); // 42
+(null); // 0
+(' '); // 0
#javascript #programming #developer