为什么在Javascript中添加两位小数会产生错误的结果? [英] Why does adding two decimals in Javascript produce a wrong result?

查看:190

这不是一个JS问题,而是一个更一般的电脑之一。浮点数不能正确存储所有的十进制数,因为它们存储的东西是二进制的
例如:

$ $ p $ 0.5是存储为b0.1
,但0.1 = 1/10因此它是1/16 +(1 / 10-1 / 16)= 1/16 + 0.0375
0.0375 = 1/32 +(0.0375-1 / 32)= 1/32 + 00625 ... etc

所以在二进制中0.1是0.00011 ...

但这是无止境的。
除了电脑必须在某个时刻停下来。因此,如果在我们的例子中,我们停在0.00011,我们有0.09375,而不是0.1。

无论如何,重要的是,这不依赖于语言,而是在计算机上。什么取决于语言是如何显示数字。通常,语言将数字四舍五入为可接受的表示形式。显然JS没有。



所以你必须做的(内存中的数字是足够准确的)只是告诉JS以很好将它们转换为文本。



您可以尝试 sprintf 函数,它可以很好地控制如何显示号码。


Possible Duplicate:
Is JavaScript’s Math broken?

Why does JS screw up this simple math?

document.write(.1 + .2)  // 0.3000000000000004
document.write(.3 + .6)  // 0.8999999999999999

The first example is greater than the correct result, while the second is less. ???!! How do you fix this? Do you have to always convert decimals into integers before performing operations? Do I only have to worry about adding (* and / don't appear to have the same problem in my tests)?

I've looked in a lot of places for answers. Some tutorials (like shopping cart forms) pretend the problem doesn't exist and just add values together. Gurus provide complex routines for various math functions or mention JS "does a poor job" in passing, but I have yet to see an explanation.

解决方案

It's not a JS problem but a more general computer one. Floating number can't store properly all decimal numbers, because they store stuff in binary For example:

0.5 is store as b0.1 
but 0.1 = 1/10 so it's 1/16 + (1/10-1/16) = 1/16 + 0.0375
0.0375 = 1/32 + (0.0375-1/32) = 1/32 + 00625 ... etc

so in binary 0.1 is 0.00011... 

but that's endless. Except the computer has to stop at some point. So if in our example we stop at 0.00011 we have 0.09375 instead of 0.1.

Anyway the point is, that doesn't depend on the language but on the computer. What depends on the language is how you display numbers. Usually, the language rounds numbers to an acceptable representation. Apparently JS doesn't.

So what you have to do (the number in memory is accurate enough) is just to tell somehow to JS to round "nicely" number when converting them to text.

You may try the sprintf function which give you a fine control of how to display a number.

这篇关于为什么在Javascript中添加两位小数会产生错误的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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