为什么 2 个 parseFloat 变量的总和给我一个不正确

Why does the sum of 2 parseFloat variables give me an incorrect decimal number(为什么 2 个 parseFloat 变量的总和给我一个不正确的十进制数)

本文介绍了为什么 2 个 parseFloat 变量的总和给我一个不正确的十进制数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这个小功能:

<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

in field 1 I enter: 221.58 in field 2 I enter: 2497.74

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

I expect the sum of 2 numbers in the input fields to be a 2 number digit: 2719.32 But the result is a incorrect number... : 2719.3199999999997

一轮就可以完成这项工作,但我只是不明白为什么代码会在这个数字上这样做......在其他数字组合上,总和是正确的......

a round would do the job, but I just don't get why the code does that on this number... On other number combinations, the sum is correct...

推荐答案

来自 浮点指南:

为什么我的数字,比如 0.1 + 0.2 加起来不是很好的 0.3,而且相反,我得到了一个奇怪的结果,比如0.30000000000000004?

因为在内部,计算机使用格式(二进制浮点)不能准确地表示一个数字像 0.1、0.2 或 0.3 一样.

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.

当代码被编译或解释,你的0.1"已经四舍五入到最接近的数字格式,这会导致一个小舍入误差甚至在计算发生.

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() 转换时,会发生舍入错误.

In your case, the rounding errors happen when the values you entered are converted by parseFloat().

为什么 0.1 + 0.4 等其他计算可以正常工作?

在这种情况下,结果 (0.5) 可以是完全表示为浮点数,它是可能的舍入误差输入数字以相互抵消- 但这不一定是可靠的(例如,当这两个数字是存储在不同大小的浮动中首先是点表示,舍入误差可能不会抵消每个其他).

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

在 0.1 + 0.3 等其他情况下,结果实际上并不是真正的 0.4,而是足够接近,0.4 是最短的更接近结果的数字比任何其他浮点数数字.然后显示多种语言该数字而不是转换实际结果回最接近小数.

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.

这篇关于为什么 2 个 parseFloat 变量的总和给我一个不正确的十进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:为什么 2 个 parseFloat 变量的总和给我一个不正确

基础教程推荐