Sub topic 7
Turning Strings into Numbers: Number(), parseInt, parseFloat, and Unary Plus
Numbers often arrive as text. Form fields, URL query strings, CSV files, environment variables, and data-* attributes all give you strings. JavaScript has four common ways to turn those strings into numbers, and they disagree on many inputs. This chapter shows the rule each one follows, where they differ, and which one to pick.
This chapter assumes you know basic JavaScript syntax, can run code in Node.js or a browser console, and understand typeof and ===. It also assumes you have read the earlier chapters on NaN and on numeric literals.
Two Families of Conversion
The four tools split into two groups:
- Whole-string conversion:
Number(value)and unary plus (+value). The entire string, after trimming whitespace, must be a valid number. If it isn't, you getNaN. - Prefix parsing:
parseInt(string, radix)andparseFloat(string). These read characters from the start of the string and stop at the first character they cannot use. They return whatever they read before stopping, and returnNaNonly when no digits come first.
console.log(Number("42")); // 42
console.log(Number("42px")); // NaN
console.log(Number("")); // 0
console.log(Number(null)); // 0
console.log(Number(undefined)); // NaN
console.log(+" 12 "); // 12
console.log(parseInt("42px", 10)); // 42
console.log(parseInt("1F", 16)); // 31
console.log(parseFloat("3.14abc")); // 3.14Number() and Unary Plus
Number(value) and +value run the same internal ToNumber conversion, so they give the same result for every input except BigInt. That case is covered below. Strings follow these rules:
- Leading and trailing whitespace is removed. This includes spaces, tabs, and newlines.
- An empty or whitespace-only string becomes
0. - The remaining text must be one of: a decimal number with an optional sign, fraction, and exponent; a
0x,0o, or0bliteral with no sign; orInfinitywith an optional sign. - Anything else becomes
NaN.
console.log(Number("1e3")); // 1000
console.log(Number(".5")); // 0.5
console.log(Number("0x1F")); // 31
console.log(Number("0b101")); // 5
console.log(Number("0o17")); // 15
console.log(Number("-0x1F")); // NaN (no sign allowed on hex)
console.log(Number("1_000")); // NaN (separators only work in source code)
console.log(Number("1,000")); // NaN
console.log(Number("-Infinity")); // -Infinity
console.log(Number("infinity")); // NaN (case-sensitive)
console.log(Number(" \n\t ")); // 0Values that are not strings follow their own rules. Objects and arrays are first converted to a primitive, usually through toString, and that result is then converted:
console.log(Number(true)); // 1
console.log(Number(false)); // 0
console.log(Number([])); // 0 ([] -> "" -> 0)
console.log(Number([7])); // 7 ([7] -> "7")
console.log(Number([1, 2])); // NaN ("1,2")
console.log(Number({})); // NaN ("[object Object]")
console.log(Number(new Date(0))); // 0 (uses valueOf, the timestamp)The BigInt and Symbol difference
Number(10n) converts a BigInt to a Number. Unary plus on a BigInt throws an error instead. Both throw for a Symbol.
console.log(Number(10n)); // 10
try {
console.log(+10n);
} catch (e) {
console.log(e instanceof TypeError); // true
}Use Number() when you want the conversion to stand out to readers, or when the value might be a BigInt. Use + for short expressions where everyone on the team knows the idiom.
parseInt(string, radix)
parseInt always converts its first argument to a string first. It then skips leading whitespace, reads an optional + or -, and reads digits that are valid in the given radix, stopping at the first character that isn't one. The radix is the number base and can be anything from 2 to 36.
console.log(parseInt(" -42abc", 10)); // -42
console.log(parseInt("3.99", 10)); // 3 (stops at ".")
console.log(parseInt("abc", 10)); // NaN (no leading digits)
console.log(parseInt("", 10)); // NaN (unlike Number(""))
console.log(parseInt("ff", 16)); // 255
console.log(parseInt("z", 36)); // 35
console.log(parseInt("101", 2)); // 5
console.log(parseInt("2", 2)); // NaN (2 is not a binary digit)
console.log(parseInt("10", 37)); // NaN (radix out of range)Always pass the radix
If you leave out the radix, or pass 0, parseInt uses base 16 when the string starts with 0x or 0X, and base 10 for everything else. Modern engines no longer treat a leading 0 as octal, but the hex rule still applies, and leaving out the radix hides what you meant. Linters such as ESLint's radix rule flag a missing radix.
console.log(parseInt("0x1F")); // 31
console.log(parseInt("-0x1F")); // -31 (signed hex works here, unlike Number)
console.log(parseInt("0x1F", 10)); // 0 (reads "0", stops at "x")
console.log(parseInt("08", 10)); // 8Gotcha: parseInt on numbers
Because parseInt converts its argument to a string, numbers that print in exponent form give strange results. Use Math.trunc to drop the fractional part of a number.
console.log(parseInt(0.0000005, 10)); // 5 (String gives "5e-7")
console.log(parseInt(1e21, 10)); // 1 (String gives "1e+21")
console.log(Math.trunc(0.0000005)); // 0Gotcha: parseInt as a callback
Array.prototype.map passes (element, index, array) to its callback. When the callback is parseInt, the index becomes the radix:
console.log(["1", "2", "3"].map(parseInt)); // [1, NaN, NaN]
console.log(["1", "2", "3"].map((s) => parseInt(s, 10))); // [1, 2, 3]
console.log(["1", "2", "3"].map(Number)); // [1, 2, 3]Index 0 means "use the default", so "1" parses. Radix 1 is invalid, and "3" is not a valid base-2 digit.
parseFloat(string)
parseFloat reads the longest leading part of the string that forms a decimal number. That can include a sign, a fraction, an exponent, or Infinity. It has no radix argument and does not understand 0x, 0o, or 0b.
console.log(parseFloat("3.14abc")); // 3.14
console.log(parseFloat("-.5e2")); // -50
console.log(parseFloat("1e3")); // 1000
console.log(parseInt("1e3", 10)); // 1 (parseInt ignores exponents)
console.log(parseFloat("0x1F")); // 0 (reads "0", stops at "x")
console.log(parseFloat("1_000")); // 1
console.log(parseFloat("Infinityx")); // Infinity
console.log(parseFloat("1.2.3")); // 1.2Side-by-Side Comparison
| Input | `Number(s)` / `+s` | `parseInt(s, 10)` | `parseFloat(s)` |
|---|---|---|---|
| `"42"` | 42 | 42 | 42 |
| `"42px"` | NaN | 42 | 42 |
| `"3.9"` | 3.9 | 3 | 3.9 |
| `"1e3"` | 1000 | 1 | 1000 |
| `""` | 0 | NaN | NaN |
| `" "` | 0 | NaN | NaN |
| `"0x1F"` | 31 | 0 | 0 |
| `"1,000"` | NaN | 1 | 1 |
| `null` | 0 | NaN | NaN |
| `true` | 1 | NaN | NaN |
A Strict Parser for User Input
Prefix parsing accepts typos without complaint. For example, parseFloat("12.5kg") returns 12.5, and a user who typed "1,000" gets 1. For input that has to be exactly a number, use whole-string conversion, reject blank strings, and reject non-finite results. The next chapter covers Number.isFinite in detail.
function parseStrictNumber(input) {
if (typeof input !== "string" || input.trim() === "") {
return null;
}
const n = Number(input);
return Number.isFinite(n) ? n : null;
}
console.log(parseStrictNumber(" 19.99 ")); // 19.99
console.log(parseStrictNumber("")); // null
console.log(parseStrictNumber("12kg")); // null
console.log(parseStrictNumber("Infinity")); // null
console.log(parseStrictNumber("0x10")); // 16If you don't want to accept hex, binary, or octal input, check the string against a regular expression before converting, for example /^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/.
Exercises
Exercise
What do Number(" "), parseInt(" ", 10), and parseFloat(" ") return, and why do they differ?
Show answer
Number(" ") returns 0, because ToNumber trims whitespace and treats an empty string as 0. parseInt and parseFloat both return NaN, because after skipping whitespace they find no leading digits.
Exercise
A CSS width is stored as "12.5px". Which call gives 12.5, and what does Number("12.5px") return?
Show answer
parseFloat("12.5px") returns 12.5. parseInt("12.5px", 10) returns 12 because it stops at the decimal point. Number("12.5px") returns NaN because the whole string is not numeric.
Exercise
Why does ["10", "10", "10"].map(parseInt) return [10, NaN, 2]?
Show answer
map passes the index as the second argument, so the calls are parseInt("10", 0), parseInt("10", 1), and parseInt("10", 2). Radix 0 means the default base 10, which gives 10. Radix 1 is outside 2–36, which gives NaN. In base 2, "10" equals 2.
Exercise
Why does parseInt(0.0000005, 10) return 5, and what should you use to drop the fractional part of a number?
Show answer
parseInt converts the number to a string first, and 0.0000005 becomes "5e-7". Parsing stops at "e", which leaves 5. Use Math.trunc(0.0000005), which returns 0.