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

第 94 期(W3C 标准-JavaScript):toFixed 方法 #97

Open
wingmeng opened this issue Aug 25, 2019 · 0 comments
Open

第 94 期(W3C 标准-JavaScript):toFixed 方法 #97

wingmeng opened this issue Aug 25, 2019 · 0 comments

Comments

@wingmeng
Copy link
Collaborator

JavaScript 中有个 toFixed() 方法,可以把 Number 类型“四舍五入”为指定小数位数的数字字符串。

但在实际使用中,这个方法的行为有时会让人匪夷所思,例如下面的表达式:

0.045.toFixed(2);

执行后,Chrome、Firefox 浏览器输出的并非预期的 0.05,而是 0.04,IE 则输出了预期的 0.05。由此可见这个方法的四舍五入是不稳定的,存在浏览器差异,这无疑会给我们的实际开发带来麻烦。如何解决?一般通用的方式就是重写这个方法,使其行为符合四舍五入规则。

var oldtoFixed = Number.prototype.toFixed;
Number.prototype.toFixed = function(digits) {
  var length = (parseFloat(this) + '').replace(/^\d+\.?/, '').length;
  var len = length > digits ? length : digits;
  var number = Number(this) + Math.pow(10, -len-1);
  return oldtoFixed.call(number, digits);
}
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