Created
September 10, 2013 02:44
-
-
Save fordlee404/6504381 to your computer and use it in GitHub Desktop.
解决由浮点数精度原因造成的 1.0-0.9!==0.1 的问题
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 通过isEqual工具方法判断数值是否相等 | |
function isEqual(number1, number2, digits){ | |
digits = digits === undefined? 10: digits; // 默认精度为10 | |
return number1.toFixed(digits) === number2.toFixed(digits); | |
} | |
isEqual(1.0-0.7, 0.3); // return true | |
// 原生扩展方式,更喜欢面向对象的风格 | |
Number.prototype.isEqual = function(number, digits){ | |
digits = digits === undefined? 10: digits; // 默认精度为10 | |
return this.toFixed(digits) === number.toFixed(digits); | |
} | |
(1.0-0.7).isEqual(0.3); // return true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment