为什么Number()以非常大的整数返回错误的值? [英] Why does Number() return wrong values with very large integers?

查看:74
本文介绍了为什么Number()以非常大的整数返回错误的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Number()函数在某些参数上返回不正确的值,如下所示:

  Number('10000000712224641')返回10000000712224640 
Number('10000000544563531')返回10000000544563532

我在Firefox,Chome,IE和Node.js的为什么会这样?

解决方案

Javascript使用64位IEEE-754二进制浮点来存储所有数字 - 如 double例如,在C#和Java中。存储整数的类型不同。 (实际实现可能会使用优化来避免始终以这种方式执行算术,但从最终用户的角度来看,结果总是,好像每个数字都被视为64位二进制浮点值。)



这意味着只有52位可用于存储有效位数,其他位用于指数和符号。通过规范化,这意味着您可以有效地存储53个精确位的值。这意味着超过2 53 -1(这是其他答案中引用的值9007199254740991),相邻数字之间的距离大于1,因此您无法准确存储所有整数。 / p>

Number() function returns incorrect values on some arguments, like this:

Number('10000000712224641') returns 10000000712224640
Number('10000000544563531') returns 10000000544563532

I tested this on Firefox, Chome, IE and Node.js. Why is this happening?

解决方案

Javascript uses 64-bit IEEE-754 binary floating point to store all numbers - like double in C# and Java, for example. There isn't a different type to store integers. (The actual implementation may use optimizations to avoid always performing arithmetic in this way, but from an end-user perspective the results will always be as if every number were treated as a 64-bit binary floating point value.)

That means only 52 bits are available to store the significand, with the other bits being used for the exponent and sign. With normalization, that means you can effectively store values with 53 significant bits of precision. That means beyond 253-1 (which is the value 9007199254740991 as quoted in other answers), the distance between "adjacent" numbers is more than 1, so you can't store all integers exactly.

这篇关于为什么Number()以非常大的整数返回错误的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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