奇怪的Javascript行为:浮点加法给出错误的答案 [英] Weird Javascript Behaviour: Floating Point Addition giving the wrong answer

查看:140
本文介绍了奇怪的Javascript行为:浮点加法给出错误的答案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

JavaScript的数学运算被破坏了吗?

这看起来真的很愚蠢,但是运行这个时,它会显示

7.300000000000001而不是7.3


  < script language =javascript> 
function buttonClicked(){
var mySum = 1.1 + 1.1 + 1.1 + 0 + 4;
alert(mySum);
}
< / script>


这会导致什么结果?我有一个非常基本的aspx页面上的JavaScript。我们实际上是使用javascript来从表单输入中添加值,这只是一个数字被打破的例子,还有很多其他的数据。



这样做吗?!?

解决方案

它与十进制值如何转换为二进制浮点数有关。 1/10变成二进制的重复小数,所以这个数字没有完美的表示,重复的操作可以暴露错误。

JavaScript使用IEEE-754浮点数, 作为记录。其他一些语言也有同样的问题。



如何处理?就你而言,也许 toPrecision()


Possible Duplicate:
Is JavaScript’s math broken?

This seems really stupid, but when running this, it will display

7.300000000000001 instead of 7.3

<script language="javascript">
    function buttonClicked() {
        var mySum = 1.1 + 1.1 + 1.1 + 0 + 4;
        alert(mySum);
    }
</script>

What would cause this? I have the javascript on a pretty basic aspx page. We are actually using javascript to add up values from form inputs, this was just an example with numbers that were breaking it, there are many others..

Any idea what could be doing this?!?

解决方案

It has to do with how decimal values are converted to binary floating point numbers. 1/10 turns into a repeating decimal in binary, so the number is not perfectly represented, and repeated operations can expose the error.

JavaScript uses IEEE-754 floating point numbers, for the record. Some other languages have the same problem.

How to deal with it? In your case, maybe toPrecision().

这篇关于奇怪的Javascript行为:浮点加法给出错误的答案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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