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

toFixed 精度问题(银行家舍入法) #65

Open
nmsn opened this issue Nov 24, 2022 · 1 comment
Open

toFixed 精度问题(银行家舍入法) #65

nmsn opened this issue Nov 24, 2022 · 1 comment

Comments

@nmsn
Copy link
Owner

nmsn commented Nov 24, 2022

使用 toFixed 保留小数时存在这样的现象

1.35.toFixed(1) // 1.4 正确
1.335.toFixed(2) // 1.33  错误
@nmsn
Copy link
Owner Author

nmsn commented Nov 24, 2022

查询得知,toFixed 使用的是银行家舍入法

所谓银行家舍入法,其实质是一种四舍六入五取偶(又称四舍六入五留双)法
https://baike.baidu.com/item/%E9%93%B6%E8%A1%8C%E5%AE%B6%E8%88%8D%E5%85%A5/4781630

四舍六入五考虑,
五后非零就进一,
五后皆零看奇偶,
五前为偶应舍去,
五前为奇要进一。

这种计算方法是 IEEE754 标准的推荐舍入标准

所以在计算金额相关的数据时,需要更加注意相关规则

但是 Chrome 验证过后并不是完全按照这个规则处理(待补充)

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