为什么JavaScript的数字*显示大数字不准确? [英] Why is JavaScript's number *display* for large numbers inaccurate?

查看:184
本文介绍了为什么JavaScript的数字*显示大数字不准确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以在JavaScript中,111111111111111111111 == 111111111111111110000。只需键入任意长号 - 至少约17位数 - 即可查看其中的操作; - )

So in JavaScript, 111111111111111111111 == 111111111111111110000. Just type any long number – at least about 17 digits – to see it in action ;-)

这是因为JavaScript使用双精度浮点数,并且无法准确表达某些非常长的数字文字。相反,这些数字可以四舍五入到最接近的可表示数字。参见例如什么是JavaScript的最高整数值可以达到而不会丢失精度?

That is because JavaScript uses double-precision floating-point numbers, and certain very long numeric literals can not be expressed accurately. Instead, those numbers get rounded to the nearest representable number possible. See e.g. What is JavaScript's highest integer value that a Number can go to without losing precision?

然而,根据IEEE-754进行数学计算,我发现每个数字都是内部[111111111111111106560,111111111111111122944]将在内部由111111111111111114752取代。但是它没有显示这个 ... 4752 号,而是显示为111111111111111110000.所以JavaScript显示了那些混淆了真实行为的尾随零。这尤其令人讨厌,因为即使是2 63 这样的数字也可以准确表示,如上所述得到舍入。

However, doing the math according to IEEE-754, I found out that every number inside [111111111111111106560, 111111111111111122944] will be replaced by 111111111111111114752 internally. But instead of showing this ...4752 number, it gets displayed as 111111111111111110000. So JavaScript is showing those trailing zeros which obfuscates the real behavior. This is especially annoying because even numbers like 263, which are accurately representable, get "rounded" as described.

所以我的问题是:为什么JavaScript在显示数字时表现得像

So my question is: Why does JavaScript behave like this when displaying the number?

推荐答案

JavaScript整数只能是+ / - 2 53 ,即:

JavaScript integers can only be +/- 253, which is:

9007199254740992

您的一个号码是

111111111111111106560

这远远超出了可以准确表示为整数的数字范围。

which is considerably outside of the range of numbers that can accurately represented as an integer.

这遵循IEEE 754:

This follows the IEEE 754:


  • 符号位:1位

  • 指数宽度:11位

  • 有效精度:53位(明确存储52位)

编辑

数字的显示有时会被JavaScript引擎舍入,是的。但是,使用 toFixed 方法可以覆盖它。 (警告,已知某些版本的IE会破坏toFixed)。

The Display of numbers is sometimes rounded by the JavaScript engine, yes. However, that can be over-ridden using the toFixed method. (Warning, toFixed is known to be broken under some versions of IE).

在您的控制台中,键入:

In your console, type:

111111111111111122944..toFixed(0)




111111111111111114752

"111111111111111114752"

这篇关于为什么JavaScript的数字*显示大数字不准确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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