控制台中的结果为4.08-1.36 [英] Result of 4.08-1.36 in console

查看:123
本文介绍了控制台中的结果为4.08-1.36的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:

JavaScript的数学是否被破坏?


我注意到一个奇怪的行为,当我尝试在Chrome控制台或Firebug中运行 4.08-1.36
结果为2.72时,控制台返回 2.7199999999999998

我想知道这怎么可能。任何想法?

解决方案

计算机以二进制代替十进制数字。正如你不能以十进制形式表示分数1/3一样,你不能完全用二进制表示分数1/10,这意味着有很多值可以完全以十进制形式表示,但不能以二进制形式表示。

您示例中的所有数字均属于此类别。在二进制中,十进制数字4.08变为100.00010100011110101110 ...,二进制数字后的那些数字永远重复。另一个值1.36变为1.01011100001010001111 ....并且它们的差值2.72变成10.10111000010100011110 ...在每种情况下也具有无限重复的二进制分数。

当转换回十进制的人类观看时,计算机会进行最接近的匹配,这并不总是准确的值。


Possible Duplicate:
Is JavaScript’s Math broken?

I noticed a weird behavior when I try to run 4.08-1.36 in the Chrome console or Firebug. The console returns 2.7199999999999998 as a result when the result should be 2.72.

I was wondering how is this possible. Any ideas?

解决方案

Computers store numbers in binary instead of decimal. Just as you cannot represent the fraction 1/3 exactly in decimal form, you cannot represent the fraction 1/10 exactly in binary, which means there are many values that can be represented exactly in decimal form but not in binary form.

All of the numbers in your example fall into this category. In binary, the decimal number 4.08 becomes 100.00010100011110101110..., where those digits after the binary point repeat forever. The other value, 1.36, becomes 1.01011100001010001111...., and their difference, 2.72, becomes 10.10111000010100011110... in each case, also with an infinitely-repeating binary fraction.

When converting back to decimal for human viewing, the computer rounds to the closest possible match, which isn't always the exact value intended.

这篇关于控制台中的结果为4.08-1.36的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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