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

查看:33
本文介绍了为什么在 Javascript 中添加两位小数会产生错误的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
JavaScript 的数学有问题吗?

为什么 JS 搞砸了这个简单的数学?

Why does JS screw up this simple math?

console.log(.1 + .2)  // 0.3000000000000004
console.log(.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)?

我在很多地方寻找答案.一些教程(如购物车表单)假装问题不存在,只是将值加在一起.大师们为各种数学函数提供了复杂的例程,或者顺便提到JS做得不好",但我还没有看到解释.​​

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.

推荐答案

这不是 JS 问题,而是更通用的计算机问题.浮点数无法正确存储所有十进制数,因为它们以二进制形式存储内容例如:

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... 

但那是无止境的.除了计算机必须在某个时候停止.因此,如果在我们的示例中,我们在 0.00011 处停止,我们将得到 0.09375 而不是 0.1.

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.

无论如何,这不取决于语言,而取决于计算机.取决于语言的是您如何显示数字.通常,该语言会将数字四舍五入为可接受的表示形式.显然 JS 没有.

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.

所以你要做的(内存中的数字足够准确)只是在将它们转换为文本时以某种方式告诉 JS 将它们很好地"舍入.

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.

你可以试试 sprintf 函数,它可以让你很好地控制如何显示数字.

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

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

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