I was wondering if JavaScript is mishandling 64-bit integers or am I doing something wrong?
我想知道JavaScript是否对64位整数处理不当,还是我做错了什么?
I have the following code:
我有以下代码:
var str = "0x4000000000000000"; //4611686018427387904 decimal
var val = parseInt(str);
alert(val);
I get this value: "4611686018427388000", which is 0x4000000000000060
得到这个值:“4611686018427388000”,即0x400000000060
2 个解决方案
#1
64
JavaScript represents numbers using IEEE-754 double-precision (64 bit) format. As I understand it this gives you 53 bits precision, or fifteen to sixteen decimal digits. Your number has more digits than JavaScript can cope with, so you end up with an approximation.
JavaScript使用IEEE-754双精度(64位)格式表示数字。据我所知,这给了你53位精度,或者15到16位小数。您的数字比JavaScript能够处理的数字要多,所以您最终得到的是一个近似值。
This isn't really "mishandling" as such, but obviously it isn't very helpful if you need full precision on large numbers. There are a few JS libraries around that can handle larger numbers, e.g., BigNumber and Int64.
这并不是真正的“错误处理”,但显然,如果您需要对大数字进行完全的精确处理,那么这并不是很有帮助。有一些JS库可以处理较大的数字,例如BigNumber和Int64。
#2
0
Chromium version 57 and later natively supports arbitrary-precision integers. This is called BigInt and is being worked on for other browsers as well. It is dramatically faster than JavaScript implementations.
Chromium版本57和后续版本支持任意精度整数。这被称为BigInt,也适用于其他浏览器。它比JavaScript实现要快得多。
#1
64
JavaScript represents numbers using IEEE-754 double-precision (64 bit) format. As I understand it this gives you 53 bits precision, or fifteen to sixteen decimal digits. Your number has more digits than JavaScript can cope with, so you end up with an approximation.
JavaScript使用IEEE-754双精度(64位)格式表示数字。据我所知,这给了你53位精度,或者15到16位小数。您的数字比JavaScript能够处理的数字要多,所以您最终得到的是一个近似值。
This isn't really "mishandling" as such, but obviously it isn't very helpful if you need full precision on large numbers. There are a few JS libraries around that can handle larger numbers, e.g., BigNumber and Int64.
这并不是真正的“错误处理”,但显然,如果您需要对大数字进行完全的精确处理,那么这并不是很有帮助。有一些JS库可以处理较大的数字,例如BigNumber和Int64。
#2
0
Chromium version 57 and later natively supports arbitrary-precision integers. This is called BigInt and is being worked on for other browsers as well. It is dramatically faster than JavaScript implementations.
Chromium版本57和后续版本支持任意精度整数。这被称为BigInt,也适用于其他浏览器。它比JavaScript实现要快得多。