javascript – 为什么2个parseFloat变量的总和给我一个不正确的十进制数

参见英文答案 > Is floating point math broken?29个
如果我有这个小功能
<script type="text/javascript">

 function printFloat(){
      var myFloatNumber1 = document.getElementById('floatNumber1');
      var myFloatNumber2 = document.getElementById('floatNumber2');
      alert(parseFloat(myFloatNumber1.value) + parseFloat(myFloatNumber2.value))
 }

</script>

<input type="text" id="floatNumber1"></input>
<input type="text" id="floatNumber2"></input>

<input type="button" onclick="printFloat()"/>

在字段1中,输入:221.58
在字段2中输入:2497.74

我期望输入字段中的2个数字的和为2位数字:2719.32
但结果是一个不正确的数字…:2719.3199999999997

一轮将做这个工作,但是我不知道为什么代码在这个数字上做到这一点…
在其他数字组合中,总和是正确的…

解决方法

The Floating-Point-Guide:

Why don’t my numbers,like 0.1 + 0.2 add up to a nice round 0.3,and
instead I get a weird result like
0.30000000000000004?

Because internally,computers use a
format (binary floating-point) that
cannot accurately represent a number
like 0.1,0.2 or 0.3 at all.

When the code is compiled or
interpreted,your “0.1” is already
rounded to the nearest number in that
format,which results in a small
rounding error even before the
calculation happens.

在您的情况下,当您输入的值通过parseFloat()转换时,会发生舍入错误.

Why do other calculations like 0.1 + 0.4 work correctly?

In that case,the result (0.5) can be
represented exactly as a
floating-point number,and it’s
possible for rounding errors in the
input numbers to cancel each other out
– But that can’t necessarily be relied upon (e.g. when those two numbers were
stored in differently sized floating
point representations first,the
rounding errors might not offset each
other).

In other cases like 0.1 + 0.3,the result actually isn’t really 0.4,but close enough that 0.4 is the shortest number that is closer to the result than to any other floating-point number. Many languages then display that number instead of converting the actual result back to the closest decimal fraction.

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...