# 深度剖析0.1 +0.2===0.30000000000000004的原因

EcmaScrpt规范定义Number的类型遵循了IEEE754-2008中的64位浮点数规则定义的小数后的有效位数至多为52位导致计算出现精度丢失问题！

0.1*2 = 0.2 ，整数位为0，且精度只到十分位，因此是0.0。

0.0001234567 = 1.234567 * 10^-4

-1的0次幂又是什么意思？

(-1)^S x Mx 2^E

S，是符号位，决定正负，0时为正数，1时为负数。
M，是指有效位数，大于1小于2。
E，是指数位。

``````(-1)^0*1.100110011(无限循环0011) * 2^-4
S = 0，M = 1.100110011(无限循环0011)，E =-4``````

``````(-1)^0*1.100110011(无限循环0011) * 2^-3
S = 0 ，M = 1.100110011(无限循环0011)，E =-3``````

IEEE 754规定，对于32位的浮点数，最高的1位是符号位S，接着的8位是指数E，剩下的23位为有效数字M。

*6.1.6
The Number Type**
The Number type has exactly 18437736874454810627 (that is, ) values, representing the double-precision 64-bit format IEEE 754-2008 values as specified in the IEEE Standard for Binary Floating-Point Arithmetic, except that the 9007199254740990 (that is, ) distinct “Not-a-Number” values of the IEEE Standard are represented in ECMAScript as a single special  value.

(-1)^01.100110011(无限循环0011) 2^-4

S = 0，M = 1.100110011(无限循环0011)，E =-4

JS中的0.1，在引擎中运算时，实质上会编译成：

`1.1001100110011001100110011001100110011001100110011001*2^-4`

0.2同理，会编译成：

`1.1001100110011001100110011001100110011001100110011001*2^- 3`

``````
-4  0.1001100110011001100110011001100110011001100110011001 ①

-3  0.1001100110011001100110011001100110011001100110011001 ②·``````

①式转化为纯小数，小数最低位的1001被高位的0000挤出有效范围，得到③式

②式转化为纯小数，小数最低位的001被高位的000挤出有效范围，得到④式

``````
0.0000100110011001100110011001100110011001100110011001 ③

+0.0001001100110011001100110011001100110011001100110011 ④

---------------------------------------------------------------------------------------------------

=0.0100110011001100110011001100110011001100110011001100 ⑤``````

0.3 / 0.1===2.9999999999999996以及0.7 * 180==125.99999999998等等。

https://segmentfault.com/a/1190000005022170

http://demon.tw/copy-paste/javascript-precision.html

http://www.ruanyifeng.com/blog/2010/06/ieee_floating-point_representation.html

http://www.css88.com/archives/7340#more-7340

http://www.ecma-international.org/ecma-262/8.0/index.html

https://en.wikipedia.org/wiki/Floating-point_arithmetic#Internal_representation

130 人关注
69 篇文章