parseInt轮回错误 [英] parseInt rounds incorrectly

查看:122
本文介绍了parseInt轮回错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 parseInt 偶然发现了这个问题,我不确定为什么会发生这种情况。

I stumbled upon this issue with parseInt and I'm not sure why this is happening.

console.log(parseInt("16980884512690999"));   // gives 16980884512691000
console.log(parseInt("169808845126909101"));​  // gives 169808845126909100

我明显没有达到JavaScript限制中的任何数字限制
Number.MAX_VALUE = 1.7976931348623157e + 308

I clearly not hitting any number limits in JavaScript limits (Number.MAX_VALUE = 1.7976931348623157e+308)

如果重要的话,运行Win 7 64位。

Running Win 7 64 bit if that matters.

我在俯瞰什么?

小提琴

推荐答案

不要将Number.MAX_VALUE与最大准确值混淆。 javascript中的所有数字都存储为64位浮点数,这意味着您可以获得高(和低)数字,但它们只能精确到某一点。

Don't confuse Number.MAX_VALUE with maximum accurate value. All numbers in javascript are stored as 64 bit floating point, which means you can get high (and low) numbers, but they'll only be accurate to a certain point.

双浮点(即Javascript)具有53位有效位精度,这意味着javascript中最高/最低肯定准确整数为+/- 9007199254740992(2 ^ 53)。高于/低于结果的数字是准确的(最后只添加0的数字,因为指数位可用于表示)。

Double floating points (i.e. Javascript's) have 53 bits of significand precision, which means the highest/lowest "certainly accurate" integer in javascript is +/-9007199254740992 (2^53). Numbers above/below that may turn out to be accurate (the ones that simply add 0's on the end, because the exponent bits can be used to represent that).

或者,用ECMAScript的话来说:注意,数量不大于2 ^ 53的所有正整数和负整数都可以在数字类型中表示(实际上,整数0有两个表示,+ 0和-0)。

Or, in the words of ECMAScript: "Note that all the positive and negative integers whose magnitude is no greater than 2^53 are representable in the Number type (indeed, the integer 0 has two representations, +0 and −0)."

更新

只是添加一点到现有问题,ECMAScript规范要求如果整数Number小于22位, .toString()将以标准十进制表示法输出(例如 169808845126909100000 在您的示例中)。如果它有22位或更多位数,它将以标准化的科学记数法输出(例如 1698088451269091000000 - 另外的0 - 输出为 1.698088451269091e + 21 )。

Just to add a bit to the existing question, the ECMAScript spec requires that if an integral Number has less than 22 digits, .toString() will output it in standard decimal notation (e.g. 169808845126909100000 as in your example). If it has 22 or more digits, it will be output in normalized scientific notation (e.g. 1698088451269091000000 - an additional 0 - is output as 1.698088451269091e+21).

这篇关于parseInt轮回错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆