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

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

问题描述

<块引用>

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

这看起来很傻,但是运行时会显示

7.300000000000001 而不是 7.3

<块引用>

<脚本语言="javascript">功能按钮点击(){var mySum = 1.1 + 1.1 + 1.1 + 0 + 4;警报(我的总和);}</脚本>

这是什么原因造成的?我在一个非常基本的 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天全站免登陆