JavaScript Reference ยท Number and BigInt
The Number() function
Reference for JavaScript Number(): how strings, booleans, null, undefined, arrays, dates and BigInts convert to numbers, plus NaN results and new Number().
Number() called as a plain function converts any value to a number primitive. It is the strict, whole-value converter: the entire string must look like a number, otherwise the result is NaN. That makes it different from parseInt() and parseFloat(), which read as much as they can from the start of a string.
Number is also the name of the built-in object that holds constants such as Number.EPSILON and helpers such as Number.isInteger(). This page covers the conversion call.
Number("42"); // 42 Number("42px"); // NaN Number(true); // 1
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
Number(value) Number() new Number(value)
| Name | Description |
|---|---|
value |
Optional. The value to convert. With no argument the result is 0. |
Return value: a number primitive when called as a function. With new, a Number wrapper object (avoid this).
Exceptions: a TypeError for a Symbol, or when an object's conversion method throws.
Usage notes
- Strings: surrounding whitespace is ignored. An empty or whitespace-only string gives
0, notNaN, which surprises many people. Decimal, exponent ("1e3"),0x,0oand0bforms are accepted; a sign is allowed only on decimal text."Infinity"converts toInfinity. - Not accepted: thousands separators, numeric separators (
"1_000"), units, or trailing text. All giveNaN. - Other primitives:
trueis1,falseandnullare0,undefinedisNaN. - Objects are first converted to a primitive. An empty array becomes
"", soNumber([])is0;[7]becomes"7";[1, 2]becomes"1,2", which isNaN. ADateconverts to its timestamp in milliseconds. - BigInt:
Number(10n)works, but values beyondNumber.MAX_SAFE_INTEGERlose precision. The unary+operator does not accept a BigInt and throws. - Check the result:
Number.isNaN(result)tells you the conversion failed. Do not compare with=== NaN. - Do not use
new Number(). It returns an object, which breaks===comparisons and is truthy even when it wraps0. - Passing
Numbertomap()works because it ignores extra arguments, unlikeparseInt.
Browser support
Number() conversion is available in every browser and JavaScript runtime. Support for the 0b and 0o string forms came with ES2015 and is universal in current engines.
Related
parseInt(),parseFloat(),Number.isInteger(),isNaN(),BigInt- Lessons: Type conversion, Numbers