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 ? #30

Open
fwon opened this issue Mar 1, 2017 · 0 comments
Open

0.1 + 0.2 == 0.3 ? #30

fwon opened this issue Mar 1, 2017 · 0 comments

Comments

@fwon
Copy link
Owner

fwon commented Mar 1, 2017

JavaScript采用的是IEEE 754规范的二进制浮点数计算方法,由于精度问题。导致0.1+0.2不等于0.3。

解决办法:设置一个误差范围值,通常称为"机器精度",对JavaScript的数字来说,这个值通常是2^-52

在ES6中,该精度值定义在Number.EPSILON中。

if (!Number.EPSILON) {
	Number.EPSILON = Math.pow(2, -52);
}

function numbersCloseEnoughToEqual(n1, n2) {
	return Math.abs(n1 - n2) < Number.EPSILON;
}

var a = 0.1 + 0.2;
var b = 0.3;

numbersCloseEnoughToEqual(a, b); //true
numbersCloseEnoughToEqual(0.0000001, 0.0000002); //false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant