为什么两个不同的数字在JavaScript中相等? [英] Why are two different numbers equal in JavaScript?
问题描述
当我突然决定尝试这样做时,我一直在搞一个JavaScript控制台:
I've been messing around with a JavaScript console, when I suddenly decided to try this:
0x100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 == 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
令人惊讶的是,它们是相等的:
Surprisingly, they're equal:
为什么会发生?它们显然是不同的数字(甚至0xFFFF...FFFF
都短一位)
Why does it happen? They're clearly different numbers (even the 0xFFFF...FFFF
is one digit shorter)
如果我将F
添加到0xFFFF...FF
,则它们不再相等:
0x100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 == 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
If I add a F
to the 0xFFFF...FF
, they're not equal anymore:
0x100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 == 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
这是预期的行为吗?
推荐答案
JavaScript中的所有数字在内部均由 64位浮点数(请参见第4.3.19 条).这意味着它可以精确表示从0
到9007199254740992
(十六进制值0x20000000000000
)的每个整数.任何大于该整数(或小于其负数的整数)的整数都可能需要四舍五入为最接近的近似值.
All numbers in JavaScript are internally represented by 64-bit floating point numbers (see §4.3.19 of the specification). That means it can exactly represent every integer from 0
up to 9007199254740992
(hex value 0x20000000000000
). Any integers greater than that (or less than it's negative counterpart) may need to be rounded to the closest approximate value.
观察:
9007199254740992 === 9007199254740993
> true
但是,在将两个数字四舍五入为足够不同的近似值时,它们在比较时仍会得出不同的值.例如:
However, two numbers that are rounded to sufficiently different approximate values still evaluate to different values when you compare them. For example:
9007199254740992 === 9007199254740994
> false
这是在第二个片段中看到的,您在其中添加了另一个F
数字.
This is what you're seeing in the second snippet where you add another F
digit.
注意:ECMAScript规范现在定义了 Number.MAX_SAFE_INTEGER
作为等于9007199254740991
的全局常量.
Note: The ECMAScript specification now define Number.MAX_SAFE_INTEGER
as a global constant equal to 9007199254740991
.
这篇关于为什么两个不同的数字在JavaScript中相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!