Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

浮点数问题,0.1+0.2 === 0.3? #13

Open
liangbus opened this issue Nov 28, 2019 · 0 comments
Open

浮点数问题,0.1+0.2 === 0.3? #13

liangbus opened this issue Nov 28, 2019 · 0 comments

Comments

@liangbus
Copy link
Owner

liangbus commented Nov 28, 2019

这个问题有多经典?看一下这个域名 0.30000000000000004.com
从前端的角度来看(从上面的链接来看,其实不止是 JS),用浮点数做计算是有风险的

0.1 + 0.2 === 0.30000000000000004 // true

因为在计算机里面,所有都是通过二进制来计算

十进制整数转二进制方法:除2取余;十进制小数转二进制方法:乘2除整

那么来看看 0.1 在计算机中是怎么表示的

0.1 * 2 = 0.2 => 0
0.2 * 2 = 0.4 => 0
0.4 * 2 = 0.8 => 0
0.8 * 2 = 1.6 => 1
0.6 * 2 = 1.2 => 1
0.2 * 2 = 0.4 => 0

这样看起来是无穷无尽的,但是实际上肯定不允许这样子,所以计算机会按某个精度去截取,所以呐,此 0.1 非彼 0.1,在计算之前,0.1 已经变不是精确的 0.1 了

那么,假如真的要计算这种小数,应该如何解决?
很简单,把小数升级(10的n次幂)

(0.1*10+0.2*10)/10 === 0.3 /true

参考:
彻底理解0.1 + 0.2 === 0.30000000000000004的背后
为什么0.1+0.2不等于0.3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant