Not All Numbers Glitter

In real life, data often comes as strings (e.g., from input fields or APIs). We need to know how to safely turn them into numbers.

1. NaN (Not a Number)

If JS couldn't compute an expression, it returns NaN. Important: NaN is not equal to anything, not even itself! So NaN == NaN returns false. To check for it, use the special function isNaN().

2. Reading " Dirty " Strings (parseInt / parseFloat)

In CSS, values often look like this: " 100px " or " 12.5em " . Number() would break here, but there is a solution:

  • parseInt("100px")100
  • parseFloat("12.5em")12.5

They read the string until they hit " garbage " . However, if the string starts with a letter (parseInt("a123")), you'll get NaN.

3. " Sanity " Check (isFinite)

The best way to check if a value is a regular number (not Infinity and not NaN).

alert( isFinite("123") ); // true
alert( isFinite(Infinity) ); // false
alert( isFinite("hello") ); // false
Tip

parseInt and parseFloat have a second argument — the radix (base). For example, parseInt("0xff", 16) returns 255.