We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
JavaScript 中有个 toFixed() 方法,可以把 Number 类型“四舍五入”为指定小数位数的数字字符串。
toFixed()
但在实际使用中,这个方法的行为有时会让人匪夷所思,例如下面的表达式:
0.045.toFixed(2);
执行后,Chrome、Firefox 浏览器输出的并非预期的 0.05,而是 0.04,IE 则输出了预期的 0.05。由此可见这个方法的四舍五入是不稳定的,存在浏览器差异,这无疑会给我们的实际开发带来麻烦。如何解决?一般通用的方式就是重写这个方法,使其行为符合四舍五入规则。
0.05
0.04
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); }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
JavaScript 中有个
toFixed()
方法,可以把 Number 类型“四舍五入”为指定小数位数的数字字符串。但在实际使用中,这个方法的行为有时会让人匪夷所思,例如下面的表达式:
执行后,Chrome、Firefox 浏览器输出的并非预期的
0.05
,而是0.04
,IE 则输出了预期的0.05
。由此可见这个方法的四舍五入是不稳定的,存在浏览器差异,这无疑会给我们的实际开发带来麻烦。如何解决?一般通用的方式就是重写这个方法,使其行为符合四舍五入规则。The text was updated successfully, but these errors were encountered: