JavaScript Type Conversion: String(), Number(), Boolean(), parseInt and Formatting Numbers
The complete guide to explicit conversions: the full conversion table, Number() vs parseInt() vs parseFloat() (and why ["1","2","3"].map(parseInt) breaks), radixes, toString(2), toFixed, toPrecision, toExponential, the unary + shortcut, and why you should never use new Number or new String.
kvi5hnuCode Sprout team member7 min readOn this page
JavaScript converts values between types constantly: text from a form field becomes a number, a number becomes text for display, any value becomes a boolean in an if. Sometimes it does this automatically (implicit conversion, article 23), and sometimes you ask for it (explicit conversion). This article covers the explicit tools and the exact rules behind them, which are also the rules the implicit conversions use.
The three conversion functions
String(x), Number(x) and Boolean(x), called without new, convert any value to the corresponding primitive type:
console.log(String(42), String(true), String(null), String([1, [2, 3]]));
console.log(Number("42"), Number(""), Number("4 2"), Number(true), Number(null));
console.log(Boolean("0"), Boolean(0), Boolean([]), Boolean(""));
42 true null 1,2,3
42 0 NaN 1 0
true false true false
Here's the complete table for primitives and common objects. Memorize the bold cells; they're the surprises.
| Value | String(v) | Number(v) | Boolean(v) |
|---|---|---|---|
undefined | "undefined" | NaN | false |
null | "null" | 0 | false |
true / false | "true" / "false" | 1 / 0 | |
"" (empty string) | 0 | false | |
" " (only whitespace) | 0 | true | |
"42", " 42 " | 42 (whitespace trimmed) | true | |
"42px", "4 2" | NaN | true | |
"0x1F", "0b101", "0o17" | 31, 5, 15 | true | |
0, -0 | "0" (sign lost) | false | |
NaN | "NaN" | false | |
Infinity | "Infinity" | true | |
123n | "123" | 123 | true (0n is false) |
Symbol("s") | "Symbol(s)" | throws TypeError | true |
[] | "" | 0 | true |
[7] | "7" | 7 | true |
[1, 2] | "1,2" | NaN | true |
{} | "[object Object]" | NaN | true |
new Date(0) | a readable date string | 0 (the timestamp) | true |
The object rows come from converting the object to a primitive first (an array becomes its toString() text, a date its timestamp), which article 24 explains.
Converting strings to numbers
There are three main tools, and they disagree on purpose:
const inputs = ["42", "42px", "3.75kg", " 12 ", "", "0x1F", "1e3", "1_000", ".5", "abc"];
console.log("input Number parseInt parseFloat");
for (const s of inputs) {
console.log(JSON.stringify(s).padEnd(10), String(Number(s)).padStart(6),
String(parseInt(s)).padStart(9), String(parseFloat(s)).padStart(11));
}
input Number parseInt parseFloat
"42" 42 42 42
"42px" NaN 42 42
"3.75kg" NaN 3 3.75
" 12 " 12 12 12
"" 0 NaN NaN
"0x1F" 31 31 0
"1e3" 1000 1 1000
"1_000" NaN 1 1
".5" 0.5 NaN 0.5
"abc" NaN NaN NaN
Number(s)(and unary+s) is strict: the whole string, after trimming whitespace, must be a valid number, or the result isNaN. But the empty or all-whitespace string becomes0, which is a classic bug source when validating form input.parseInt(s, radix)is lenient: it skips leading whitespace, reads as many digits as it can, and ignores the rest. It returns integers only and givesNaNif no digits are found (so""givesNaN).parseFloat(s)is lenient likeparseIntbut reads decimals and exponents. It only understands base 10 (so"0x1F"is0).- Numeric separators (
1_000) are valid only in source code, not in strings any of these parse.
Which to use? For validating input, use Number() and reject the empty string explicitly. For extracting a number from the start of a string like "42px" or "3.75kg", use parseInt or parseFloat.
function toQuantity(text) {
const trimmed = text.trim();
if (trimmed === "") return null; // Number("") would be 0
const n = Number(trimmed);
return Number.isInteger(n) && n > 0 ? n : null;
}
console.log(toQuantity("3"), toQuantity(""), toQuantity("2.5"), toQuantity("3 apples"), toQuantity("1e2"));
3 null null null 100
Note "1e2" is accepted as 100: exponent notation is valid number syntax. If you need digits only, test with a regular expression such as /^\d+$/ first.

Always pass a radix to parseInt
parseInt's second argument is the radix (base), from 2 to 36. Without it, strings starting with 0x are read as hexadecimal and everything else as decimal. Passing the radix makes the intent explicit, and ESLint's radix rule asks for it:
console.log(parseInt("ff", 16), parseInt("777", 8), parseInt("1011", 2), parseInt("zz", 36));
console.log(parseInt("08", 10)); // leading zeros are fine in base 10
console.log(parseInt("12", 2)); // "2" isn't a binary digit: stops after "1"
console.log(["1", "2", "3"].map(parseInt)); // a famous trap
console.log(["1", "2", "3"].map(Number)); // the fix
255 511 11 1295
8
1
[ 1, NaN, NaN ]
[ 1, 2, 3 ]
Why does ["1", "2", "3"].map(parseInt) give [1, NaN, NaN]? map calls its callback with three arguments: the element, the index and the array. So the calls are parseInt("1", 0), parseInt("2", 1) and parseInt("3", 2). A radix of 0 means "use the default" (10), giving 1; radix 1 is invalid, giving NaN; and "3" isn't a valid digit in base 2, giving NaN. Use map(Number) or map(s => parseInt(s, 10)).
One more parseInt trap: it converts its argument to a string first. parseInt(0.0000005) is 5, because that number's string form is "5e-7". Use Math.trunc to drop the fraction of a number.
Converting numbers to strings
String(n) and n.toString() give the shortest representation that round-trips (article 12), switching to exponent notation for very large (≥ 10^21) or very small (< 10^-6) magnitudes. toString(radix) converts to another base:
console.log((255).toString(16), (255).toString(2), (255).toString(36));
console.log((0.5).toString(2), (-10).toString(16));
console.log((5).toString(2).padStart(8, "0")); // a fixed-width binary string
console.log(String(1e21), String(0.0000001));
ff 11111111 73
0.1 -a
00000101
1e+21 1e-7
Calling a method on a number literal needs care: 5.toString() is a syntax error because the dot is read as a decimal point. Write (5).toString(), 5..toString() or 5 .toString().
Formatting with toFixed, toPrecision and toExponential
These three methods return strings and round as needed:
| Method | Controls | 9876.54321 gives |
|---|---|---|
toFixed(d) | digits after the decimal point (0 to 100) | toFixed(2) → "9876.54" |
toPrecision(p) | total significant digits (1 to 100) | toPrecision(6) → "9876.54", toPrecision(2) → "9.9e+3" |
toExponential(d) | digits after the point, in exponent form | toExponential(1) → "9.9e+3" |
const reading = 9876.54321;
console.log(reading.toFixed(0), reading.toFixed(2), reading.toFixed(6));
console.log(reading.toPrecision(2), reading.toPrecision(6), reading.toPrecision(12));
console.log(reading.toExponential(1), reading.toExponential(4));
console.log((0.000123).toPrecision(2), (2.5e-7).toFixed(9), (1e21).toFixed(2));
9877 9876.54 9876.543210
9.9e+3 9876.54 9876.54321000
9.9e+3 9.8765e+3
0.00012 0.000000250 1e+21
toPrecision switches to exponent notation when the integer part needs more digits than you asked for. toFixed gives up and returns exponent form for numbers of 10^21 or more. All of them pad with zeros when asked for more digits than the value has, and all of them round the stored binary value (article 12 explains why (1.005).toFixed(2) is "1.00").
For anything shown to users, prefer Intl.NumberFormat or toLocaleString, which add locale-correct separators, currencies, percentages and compact notation:
console.log((1234567.891).toLocaleString("en-US"));
console.log((1234567.891).toLocaleString("de-DE"));
console.log((0.256).toLocaleString("en-US", { style: "percent" }));
console.log(new Intl.NumberFormat("en-US", { notation: "compact" }).format(1234567));
1,234,567.891
1.234.567,891
26%
1.2M
Shortcut idioms
You'll see operators used as quick conversions in existing code:
| Idiom | Equivalent | Notes |
|---|---|---|
+x | Number(x) | throws for BigInt |
x - 0, x * 1 | Number(x) | less clear |
"" + x or `${x}` | String(x) | "" + x uses the "default" hint for objects (article 24) |
!!x | Boolean(x) | |
~~x, x | 0 | truncate to a 32-bit integer | wrong outside ±2^31! use Math.trunc |
Number(x), String(x) and Boolean(x) say what they do, and that clarity usually beats saving a few characters. The bitwise tricks are worse than unclear: ~~3000000000 is -1294967296, because bitwise operators work on 32-bit integers.
Wrapper objects: never use new
String, Number and Boolean can also be called with new, which creates a wrapper object instead of a primitive. These exist only for historical reasons, and they cause bugs:
const primitive = Number("5");
const wrapper = new Number("5");
console.log(typeof primitive, typeof wrapper);
console.log(wrapper + 1); // unwraps for arithmetic
console.log(wrapper === 5, wrapper == 5); // strict equality fails
console.log(new Number(5) === new Number(5)); // two different objects
console.log(new Boolean(false) ? "truthy!" : "falsy");
number object
6
false true
false
truthy!
They're objects, so typeof says "object", === compares identity, and they're always truthy. Use the functions without new to convert; BigInt and Symbol don't even allow new.
Common questions
What's the best way to convert a string to a number?
Number(s) (or unary +s) when the whole string must be numeric, after checking for empty strings. parseInt(s, 10) or parseFloat(s) when you want to read a number at the start of a string with trailing text, like "42px".
Why does Number("") return 0 instead of NaN?
That's how the specification defines converting a string that contains no characters (or only whitespace): its mathematical value is 0. It's a historical decision that makes empty form fields look like valid zeros, so check for empty input before converting.
Is toString() the same as String()?
Almost. String(x) works for every value, including null and undefined (giving "null" and "undefined") and symbols. x.toString() throws a TypeError for null and undefined, since they have no methods. toString also accepts a radix for numbers.
How do I convert a number to a string with leading zeros?
String(n).padStart(width, "0"), for example String(7).padStart(3, "0") is "007". For negative numbers, pad the absolute value and add the sign back.
Summary
String(),Number()andBoolean()withoutnewconvert anything; learn the surprises:Number(null)andNumber("")are 0,Number([])is 0,Number([7])is 7,Number(undefined)is NaN.Number()is strict about the whole string;parseInt/parseFloatread a leading number and ignore the rest.- Always pass a radix to
parseInt, and never passparseIntdirectly tomap. toString(radix)changes base;toFixed,toPrecisionandtoExponentialformat with rounding;Intl.NumberFormatformats for humans.- Prefer explicit conversion functions over
+x,"" + xand bitwise tricks; never usenew Number/String/Boolean.
Practice Questions
What do Number("12px"), parseInt("12px") and parseFloat("12.5px") return?
Answer
NaN, 12 and 12.5.
Why does ["10", "10", "10"].map(parseInt) return [10, NaN, 2]?
Answer
map passes the index as parseInt's radix: parseInt("10", 0) is 10 (radix 0 means default), parseInt("10", 1) is NaN (invalid radix) and parseInt("10", 2) is 2 (binary 10).
How do you convert the number 10 to the binary string "1010", and back?
Answer
(10).toString(2) gives "1010", and parseInt("1010", 2) gives 10.
What do Number(null), Number(undefined) and Number([]) return?
Answer
0, NaN and 0.
What does (1234.5678).toFixed(2) return, and what type is it?
Answer
"1234.57", a string. Convert it back with Number(...) if you need a number.
Previous: Primitives vs References in JavaScript: Copying, Comparing and Mutating Values
Next: Implicit Type Coercion and == in JavaScript: The Rules Behind the Surprises

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.