数字

Number 值代表浮点数,如 37-9.25

¥**Number** values represent floating-point numbers like 37 or -9.25.

Number 构造函数包含用于处理数字的常量和方法。其他类型的值可以使用 Number() 函数转换为数字。

¥The Number constructor contains constants and methods for working with numbers. Values of other types can be converted to numbers using the Number() function.

描述

¥Description

数字最常以文字形式表示,例如 2553.14159词汇语法 包含更详细的参考。

¥Numbers are most commonly expressed in literal forms like 255 or 3.14159. The lexical grammar contains a more detailed reference.

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

JavaScript 代码中的数字文字(如 37)是浮点值,而不是整数。日常使用中没有单独的整数类型。(JavaScript 也有 BigInt 类型,但它并不是为了取代日常使用的 Number 而设计的。37 仍然是一个数字,而不是 BigInt。)

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

当用作函数时,Number(value) 将字符串或其他值转换为 Number 类型。如果该值无法转换,则返回 NaN

¥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 returns NaN.

js
Number("123"); // returns the number 123
Number("123") === 123; // true

Number("unicorn"); // NaN
Number(undefined); // NaN

数字编码

¥Number encoding

JavaScript Number 类型是一个 双精度 64 位二进制格式 IEEE 754 值,就像 Java 或 C# 中的 double 一样。这意味着它可以表示小数值,但存储的数字的大小和精度有一些限制。简而言之,IEEE 754 双精度数使用 64 位来表示 3 个部分:

¥The JavaScript Number type is a double-precision 64-bit binary format IEEE 754 value, like double 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 位用于符号(正或负)
  • 11 位指数(-1022 到 1023)
  • 52 位尾数(表示 0 到 1 之间的数字)

尾数(也称为有效数字)是代表实际值(有效数字)的数字部分。指数是尾数应乘以的 2 的幂。将其视为科学记数法:

¥The mantissa (also called significand) 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 ) 2 exponent \text{Number} = ({-1})^{\text{sign}} \cdot (1 + \text{mantissa}) \cdot 2^{\text{exponent}}

尾数以 52 位存储,解释为二进制小数中 1.… 之后的数字。因此,尾数的精度为 2-52(可通过 Number.EPSILON 获得),即小数点后约 15 至 17 位;高于该精度级别的算术受 rounding 约束。

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

一个数字可以容纳的最大值是 21023 × (2 - 2-52)(指数为 1023,尾数为 0.1111…,基数为 2),其中 可通过 Number.MAX_VALUE 获得。高于该值的值将替换为特殊数字常量 Infinity

¥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 via Number.MAX_VALUE. Values higher than that are replaced with the special number constant Infinity.

整数只能在不损失精度的情况下表示 -253 + 1 到 253 范围内 - 1,包含(可通过 Number.MIN_SAFE_INTEGERNumber.MAX_SAFE_INTEGER 获得),因为尾数只能容纳 53 位(包括前导 1)。

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

有关这方面的更多详细信息,请参阅 ECMAScript 标准

¥More details on this are described in the ECMAScript standard.

数字强制

¥Number coercion

许多期望数字的内置操作首先将其参数强制为数字(这在很大程度上是 Number 对象的行为与数字基元类似的原因)。操作 可概括如下:

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

  • 数字按原样返回。
  • undefined 变成 NaN
  • null 变成 0
  • true 变成 1false 变成 0
  • 通过解析字符串来转换它们,就像它们包含 数字字面量 一样。解析失败导致 NaN。与实际数字文字相比,存在一些细微差别:
    • 前导和尾随空格/行终止符将被忽略。
    • 前导 0 数字不会导致数字变成八进制文字(或在严格模式下被拒绝)。
    • 允许在字符串的开头使用 +- 来指示其符号。(在实际代码中,它们是文字的 "看起来像" 部分,但实际上是单独的一元运算符。)但是,该符号只能出现一次,并且后面不能有空格。
    • Infinity-Infinity 被识别为文字。在实际代码中,它们是全局变量。
    • 空或仅包含空格的字符串将转换为 0
    • 数字分隔符 是不允许的。
  • BigInts 抛出 TypeError 以防止意外的隐式强制转换导致精度损失。
  • 符号TypeError
  • 对象首先通过按顺序调用 [@@toPrimitive]()(以 "number" 作为提示)、valueOf()toString() 方法来实现 转换为原始类型。然后将得到的原语转换为数字。

在 JavaScript 中,有两种方法可以达到几乎相同的效果。

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

  • 一元加+x 完全执行上面解释的数字强制步骤来转换 x
  • Number() 功能:Number(x) 使用相同的算法来转换 x,只不过 BigInts 不会抛出 TypeError,而是返回它们的数值,但可能会损失精度。

Number.parseFloat()Number.parseInt()Number() 类似,但仅转换字符串,并且解析规则略有不同。例如,parseInt() 不识别小数点,parseFloat() 不识别 0x 前缀。

¥Number.parseFloat() and Number.parseInt() are similar to Number() but only convert strings, and have slightly different parsing rules. For example, parseInt() doesn't recognize the decimal point, and parseFloat() doesn't recognize the 0x prefix.

整数转换

¥Integer conversion

某些操作需要整数,尤其是那些使用数组/字符串索引、日期/时间组件和数字基数的操作。执行上述数字强制转换步骤后,结果为 truncated 为整数(通过丢弃小数部分)。如果数字为 ±Infinity,则按原样返回。如果数字是 NaN-0,则返回为 0。因此,结果始终是整数(不是 -0)或 ±Infinity。

¥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 is truncated to an integer (by discarding the fractional part). If the number is ±Infinity, it's returned as-is. If the number is NaN or -0, it's returned as 0. The result is therefore always an integer (which is not -0) or ±Infinity.

值得注意的是,当转换为整数时,undefinednull 都变成了 0,因为 undefined 转换为 NaNNaN 也变成了 0

¥Notably, when converted to integers, both undefined and null become 0, because undefined is converted to NaN, which also becomes 0.

固定宽度数字转换

¥Fixed-width number conversion

JavaScript 有一些处理整数二进制编码的底层函数,尤其是 按位运算符TypedArray 对象。位运算符始终将操作数转换为 32 位整数。在这些情况下,将值转换为数字后,首先对小数部分进行 truncating,然后采用整数的二进制补码编码中的最低位,将数字标准化为给定宽度。

¥JavaScript has some lower-level functions that deal with the binary encoding of integer numbers, most notably bitwise operators and TypedArray 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 first truncating 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()

创建新的 Number 值。

Number 作为构造函数(与 new)被调用时,它会创建一个 Number 对象,该对象不是基元。例如,typeof new Number(42) === "object"new Number(42) !== 42(尽管是 new Number(42) == 42)。

¥When Number is called as a constructor (with new), it creates a Number object, which is not a primitive. For example, typeof new Number(42) === "object", and new Number(42) !== 42 (although new Number(42) == 42).

警告:你应该很少发现自己使用 Number 作为构造函数。

¥Warning: You should rarely find yourself using Number as a constructor.

静态属性

¥Static properties

Number.EPSILON

两个可表示数字之间的最小间隔。

Number.MAX_SAFE_INTEGER

JavaScript 中的最大安全整数 (253 - 1)。

Number.MAX_VALUE

可表示的最大正数。

Number.MIN_SAFE_INTEGER

JavaScript 中的最小安全整数 (-(253 - 1))。

Number.MIN_VALUE

可表示的最小正数,即最接近零的正数(实际上并不为零)。

Number.NaN

特殊 "不是一个数字" 值。

Number.NEGATIVE_INFINITY

表示负无穷大的特殊值。溢出时返回。

Number.POSITIVE_INFINITY

代表无穷大的特殊值。溢出时返回。

静态方法

¥Static methods

Number.isFinite()

判断传入的值是否是有限数。

Number.isInteger()

判断传入的值是否为整数。

Number.isNaN()

判断传入的值是否为 NaN

Number.isSafeInteger()

判断传入的值是否是安全整数(-(253 - 1) 和 253 之间的数字 - 1).

Number.parseFloat()

这与全局 parseFloat() 功能相同。

Number.parseInt()

这与全局 parseInt() 功能相同。

实例属性

¥Instance properties

这些属性在 Number.prototype 上定义并由所有 Number 实例共享。

¥These properties are defined on Number.prototype and shared by all Number instances.

Number.prototype.constructor

创建实例对象的构造函数。对于 Number 实例,初始值为 Number 构造函数。

实例方法

¥Instance methods

Number.prototype.toExponential()

返回以指数表示法表示数字的字符串。

Number.prototype.toFixed()

返回以定点表示法表示数字的字符串。

Number.prototype.toLocaleString()

返回一个字符串,其中包含该数字的语言敏感表示形式。覆盖 Object.prototype.toLocaleString() 方法。

Number.prototype.toPrecision()

以定点或指数表示法返回表示指定精度的数字的字符串。

Number.prototype.toString()

返回表示指定基数("base")中指定对象的字符串。覆盖 Object.prototype.toString() 方法。

Number.prototype.valueOf()

返回指定对象的原始值。覆盖 Object.prototype.valueOf() 方法。

示例

¥Examples

使用 Number 对象为数值变量赋值

¥Using the Number object to assign values to numeric variables

以下示例使用 Number 对象的属性为多个数值变量赋值:

¥The following example uses the Number 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;

Number 的整数范围

¥Integer range for Number

以下示例显示了可以表示为 Number 对象的最小和最大整数值。

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

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

解析已序列化为 JSON 的数据时,如果 JSON 解析器将其强制转换为 Number 类型,则超出此范围的整数值可能会被损坏。

¥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 to Number type.

一个可能的解决方法是使用 String

¥A possible workaround is to use String instead.

更大的数字可以使用 BigInt 类型来表示。

¥Larger numbers can be represented using the BigInt type.

使用 Number() 转换 Date 对象

¥Using Number() to convert a Date object

以下示例使用 Number 作为函数将 Date 对象转换为数值:

¥The following example converts the Date object to a numerical value using Number as a function:

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

这会记录 819199440000

¥This logs 819199440000.

将数字字符串和 null 转换为数字

¥Convert numeric strings and null to numbers

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

规范

Specification
ECMAScript Language Specification
# sec-number-objects

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看