Values from forms, URLs and storage are strings. Before doing maths, convert them.
Number()
Converts the whole string, or gives NaN.
console.log(Number("42")); // → 42
console.log(Number("3.14")); // → 3.14
console.log(Number(" 7 ")); // → 7
console.log(Number("")); // → 0
console.log(Number("12px")); // → NaN
console.log(Number("abc")); // → NaN
Note that an empty string becomes 0, which can hide a problem.
parseInt
Reads whole numbers from the start of the text and stops at the first invalid character.
console.log(parseInt("42px")); // → 42
console.log(parseInt("3.99")); // → 3
console.log(parseInt("px42")); // → NaN
console.log(parseInt("101", 2)); // → 5
The second argument is the radix (the number base). Always pass 10 when parsing decimal text, to be explicit: parseInt("08", 10).
parseFloat
Same idea, but it keeps decimals.
console.log(parseFloat("3.14abc")); // → 3.14
console.log(parseFloat(".5")); // → 0.5
console.log(parseFloat("abc")); // → NaN
Which one?
| Situation | Use |
|---|---|
| The whole string must be a number | Number() |
Text like "20px" or "15%" | parseFloat() or parseInt(x, 10) |
| Whole numbers only | parseInt(x, 10) |
Always check the result
function readAge(text) {
const age = Number(text);
if (text.trim() === "" || Number.isNaN(age)) {
return null;
}
return age;
}
console.log(readAge("25")); // → 25
console.log(readAge("abc")); // → null
console.log(readAge("")); // → null
The unary plus shortcut
+"42" also converts to a number. It works like Number(), but Number() is clearer to read.
Forgetting that inputs are strings
input.value + 1 joins text: "5" + 1 is "51". Convert first: Number(input.value) + 1. You will use this in the calculator project.