为什么固定()舍入是如此奇怪 [英] Why toFixed() rounding is so strange

查看:65
本文介绍了为什么固定()舍入是如此奇怪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Chrome 29.0.1547.57:

Chrome 29.0.1547.57:

0.0095 .toFixed(3) // "0.009"
0.1095 .toFixed(3) // "0.110"
1.1095 .toFixed(3) // "1.109"

这个函数出了什么问题?

我知道我可以编写自己的函数,这里的问题是为什么股票函数如此错误?
根据MDN,它是在JS 1.5中实现的,所以它不是新的。或者我可能不理解这个函数吗?

What's wrong with this function?
I know that I can write my own function, the question here is why stock function is so buggy? According to MDN it was implemented in JS 1.5 so it's not new. Or maybe I don't understand this function right?

推荐答案

问题是大多数小数部分的二进制浮点表示不是精确。 0.0095 的内部表示实际上可能类似于 0.00949999 ,所以 toFixed 向下舍入,而 0.1095 可能是 0.109500001 ,它会向上舍入。

The problem is that binary floating point representation of most decimal fractions is not exact. The internal representation of 0.0095 may actually be something like 0.00949999, so toFixed rounds down, while 0.1095 might be 0.109500001, which rounds up.

请参阅 Javascript toFixed Not Rounding

这篇关于为什么固定()舍入是如此奇怪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆