Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

Number

BaselineWidely available

Number values represent floating-point numbers like37 or-9.25.

TheNumber constructor contains constants and methods for working with numbers. Values of other types can be converted to numbers using theNumber() function.

Description

Numbers are most commonly expressed in literal forms like255 or3.14159. Thelexical grammar contains a more detailed reference.

js
255; // two-hundred and fifty-five255.0; // same number255 === 255.0; // true255 === 0xff; // true (hexadecimal notation)255 === 0b11111111; // true (binary notation)255 === 0.255e3; // true (decimal exponential notation)

A number literal like37 in JavaScript code is a floating-point value, not an integer. There is no separate integer type in common everyday use. (JavaScript also has aBigInt type, but it's not designed to replace Number for everyday uses.37 is still a number, not a BigInt.)

When used as a function,Number(value) converts a string or other value to the Number type. If the value can't be converted, it returnsNaN.

js
Number("123"); // returns the number 123Number("123") === 123; // trueNumber("unicorn"); // NaNNumber(undefined); // NaN

Number encoding

The JavaScriptNumber type is adouble-precision 64-bit binary format IEEE 754 value, likedouble in Java or C#. This means it can represent fractional values, but there are some limits to the stored number's magnitude and precision. Very briefly, an IEEE 754 double-precision number uses 64 bits to represent 3 parts:

  • 1 bit for thesign (positive or negative)
  • 11 bits for theexponent (-1022 to 1023)
  • 52 bits for themantissa (representing a number between 0 and 1)

The mantissa (also calledsignificand) is the part of the number representing the actual value (significant digits). The exponent is the power of 2 that the mantissa should be multiplied by. Thinking about it as scientific notation:

Number=(1)sign(1+mantissa)2exponent\text{Number} = ({-1})^{\text{sign}} \cdot (1 + \text{mantissa}) \cdot 2^{\text{exponent}}

The mantissa is stored with 52 bits, interpreted as digits after1.… in a binary fractional number. Therefore, the mantissa's precision is 2-52 (obtainable viaNumber.EPSILON), or about 15 to 17 decimal places; arithmetic above that level of precision is subject torounding.

The largest value a number can hold is 21023 × (2 - 2-52) (with the exponent being 1023 and the mantissa being 0.1111… in base 2), which is obtainable viaNumber.MAX_VALUE. Values higher than that are replaced with the special number constantInfinity.

Integers can only be represented without loss of precision in the range -253 + 1 to 253 - 1, inclusive (obtainable viaNumber.MIN_SAFE_INTEGER andNumber.MAX_SAFE_INTEGER), because the mantissa can only hold 53 bits (including the leading 1).

More details on this are described in theECMAScript standard.

Number coercion

Many built-in operations that expect numbers first coerce their arguments to numbers (which is largely whyNumber objects behave similarly to number primitives).The operation can be summarized as follows:

  • Numbers are returned as-is.
  • undefined turns intoNaN.
  • null turns into0.
  • true turns into1;false turns into0.
  • Strings are converted by parsing them as if they contain anumber literal. Parsing failure results inNaN. There are some minor differences compared to an actual number literal:
    • Leading and trailing whitespace/line terminators are ignored.
    • A leading0 digit does not cause the number to become an octal literal (or get rejected in strict mode).
    • + and- are allowed at the start of the string to indicate its sign. (In actual code, they "look like" part of the literal, but are actually separate unary operators.) However, the sign can only appear once, and must not be followed by whitespace.
    • Infinity and-Infinity are recognized as literals. In actual code, they are global variables.
    • Empty or whitespace-only strings are converted to0.
    • Numeric separators are not allowed.
  • BigInts throw aTypeError to prevent unintended implicit coercion causing loss of precision.
  • Symbols throw aTypeError.
  • Objects are firstconverted to a primitive by calling their[Symbol.toPrimitive]() (with"number" as hint),valueOf(), andtoString() methods, in that order. The resulting primitive is then converted to a number.

There are two ways to achieve nearly the same effect in JavaScript.

  • Unary plus:+x does exactly the number coercion steps explained above to convertx.
  • TheNumber() function:Number(x) uses the same algorithm to convertx, except thatBigInts don't throw aTypeError, but return their number value, with possible loss of precision.

Number.parseFloat() andNumber.parseInt() are similar toNumber() but only convert strings, and have slightly different parsing rules. For example,parseInt() doesn't recognize the decimal point, andparseFloat() doesn't recognize the0x prefix.

Integer conversion

Some operations expect integers, most notably those that work with array/string indices, date/time components, and number radixes. After performing the number coercion steps above, the result istruncated to an integer (by discarding the fractional part). If the number is ±Infinity, it's returned as-is. If the number isNaN or-0, it's returned as0. The result is therefore always an integer (which is not-0) or ±Infinity.

Notably, when converted to integers, bothundefined andnull become0, becauseundefined is converted toNaN, which also becomes0.

Fixed-width number conversion

JavaScript has some lower-level functions that deal with the binary encoding of integer numbers, most notablybitwise operators andTypedArray objects. Bitwise operators always convert the operands to 32-bit integers. In these cases, after converting the value to a number, the number is then normalized to the given width by firsttruncating the fractional part and then taking the lowest bits in the integer's two's complement encoding.

js
new Int32Array([1.1, 1.9, -1.1, -1.9]); // Int32Array(4) [ 1, 1, -1, -1 ]new Int8Array([257, -257]); // Int8Array(2) [ 1, -1 ]// 257 = 0001 0000 0001//     =      0000 0001 (mod 2^8)//     = 1// -257 = 1110 1111 1111//      =      1111 1111 (mod 2^8)//      = -1 (as signed integer)new Uint8Array([257, -257]); // Uint8Array(2) [ 1, 255 ]// -257 = 1110 1111 1111//      =      1111 1111 (mod 2^8)//      = 255 (as unsigned integer)

Constructor

Number()

CreatesNumber objects. When called as a function, it returns primitive values of type Number.

Static properties

Number.EPSILON

The smallest interval between two representable numbers.

Number.MAX_SAFE_INTEGER

The maximum safe integer in JavaScript (253 - 1).

Number.MAX_VALUE

The largest positive representable number.

Number.MIN_SAFE_INTEGER

The minimum safe integer in JavaScript (-(253 - 1)).

Number.MIN_VALUE

The smallest positive representable number—that is, the positive number closest to zero (without actually being zero).

Number.NaN

Special "NotaNumber" value.

Number.NEGATIVE_INFINITY

Special value representing negative infinity. Returned on overflow.

Number.POSITIVE_INFINITY

Special value representing infinity. Returned on overflow.

Static methods

Number.isFinite()

Determine whether the passed value is a finite number.

Number.isInteger()

Determine whether the passed value is an integer.

Number.isNaN()

Determine whether the passed value isNaN.

Number.isSafeInteger()

Determine whether the passed value is a safe integer (number between -(253 - 1) and 253 - 1).

Number.parseFloat()

This is the same as the globalparseFloat() function.

Number.parseInt()

This is the same as the globalparseInt() function.

Instance properties

These properties are defined onNumber.prototype and shared by allNumber instances.

Number.prototype.constructor

The constructor function that created the instance object. ForNumber instances, the initial value is theNumber constructor.

Instance methods

Number.prototype.toExponential()

Returns a string representing the number in exponential notation.

Number.prototype.toFixed()

Returns a string representing the number in fixed-point notation.

Number.prototype.toLocaleString()

Returns a string with a language sensitive representation of this number. Overrides theObject.prototype.toLocaleString() method.

Number.prototype.toPrecision()

Returns a string representing the number to a specified precision in fixed-point or exponential notation.

Number.prototype.toString()

Returns a string representing the specified object in the specifiedradix ("base"). Overrides theObject.prototype.toString() method.

Number.prototype.valueOf()

Returns the primitive value of the specified object. Overrides theObject.prototype.valueOf() method.

Examples

Using the Number object to assign values to numeric variables

The following example uses theNumber object's properties to assign values to several numeric variables:

js
const biggestNum = Number.MAX_VALUE;const smallestNum = Number.MIN_VALUE;const infiniteNum = Number.POSITIVE_INFINITY;const negInfiniteNum = Number.NEGATIVE_INFINITY;const notANum = Number.NaN;

Integer range for Number

The following example shows the minimum and maximum integer values that can be represented asNumber object.

js
const biggestInt = Number.MAX_SAFE_INTEGER; // (2**53 - 1) => 9007199254740991const smallestInt = Number.MIN_SAFE_INTEGER; // -(2**53 - 1) => -9007199254740991

When parsing data that has been serialized to JSON, integer values falling outside of this range can be expected to become corrupted when JSON parser coerces them toNumber type.

A possible workaround is to useString instead.

Larger numbers can be represented using theBigInt type.

Using Number() to convert a Date object

The following example converts theDate object to a numerical value usingNumber as a function:

js
const d = new Date("1995-12-17T03:24:00");console.log(Number(d));

This logs819199440000.

Convert numeric strings and null to numbers

js
Number("123"); // 123Number("123") === 123; // trueNumber("12.3"); // 12.3Number("12.00"); // 12Number("123e-1"); // 12.3Number(""); // 0Number(null); // 0Number("0x11"); // 17Number("0b11"); // 3Number("0o11"); // 9Number("foo"); // NaNNumber("100a"); // NaNNumber("-Infinity"); // -Infinity

Specifications

Specification
ECMAScript® 2026 Language Specification
# sec-number-objects

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp