问题
The ECMAScript Number type has exactly 18437736874454810627 values.
Why did they come to this number (18437736874454810627)? In other words, because computers are usually based on binary system, then almost all the numbers (like bit, byte, int16, int32, etc) are based on 2. But I can't see how we can get from 18437736874454810627 to 2.
回答1:
Because a floating point number used by JavaScript has a fixed number of bits, used as explained in the ECMA standard (page 41 of the PDF, or page 29 as written in the footer).
The Number type has exactly 18437736874454810627 (that is, 2^64 - 2^53 + 3) values, representing the double-precision 64-bit format IEEE 754 values as specified in the IEEE Standard for Binary Floating-Point Arithmetic, except that the 9007199254740990 (that is, 2^53 - 2) distinct "Not-a-Number" values of the IEEE Standard are represented in ECMAScript as a single special NaN value.
回答2:
According to my understanding to the specification ECMA Section 8.5 - The Number Type, there are 3 kinds of representations to the Javascript Number, namely:
- NaN
- infinity
- finite numbers
Let's read again a few excerpts from the specification:
the 9007199254740990 (that is, 253−2) distinct “Not-a-Number” values of the IEEE Standard are represented in ECMAScript as a single special NaN value. [...] all NaN values are indistinguishable from each other.
Note that NaN is actually 1 single special value although multiple values are used to represent NaNs.
There are two other special values, called positive Infinity and negative Infinity.
This is simple and obvious that we have 2 infinity values.
The other 18437736874454810624 (that is, 264−253) values are called the finite numbers.
And there are 18437736874454810624 finite numbers.
So, adding up all the numbers: 1 + 2 + 18437736874454810624 = 18437736874454810627
回答3:
JavaScript uses IEEE-754 numbers which only offer 53 bits of precision. See the "Double Precision" table in that article. Also see this StackOverflow question.
回答4:
In javascript, 9007199254740990 of those values are NaN .(The IEEE Standard for 64 bit Binary Floating-Point Arithmetic defines a value for all but one NaN)
来源:https://stackoverflow.com/questions/8105196/get-the-number-18437736874454810627