Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/docker/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
带减法的Javascript toFixed行为_Javascript_Rounding_Tofixed - Fatal编程技术网

带减法的Javascript toFixed行为

带减法的Javascript toFixed行为,javascript,rounding,tofixed,Javascript,Rounding,Tofixed,我在我的应用程序中操作了很多数字。对于这种特殊情况,我要做的是:检索两个数字列表,对每个列表进行平均,然后减去两个平均值。为了避免像3.333这样的平均值,我在结果中使用.toFixed(3) 下面是它的外观: // I found this function somewhere on Stackoverflow Array.prototype.average = function() { if(this.length == 0){ return 0; } else{

我在我的应用程序中操作了很多数字。对于这种特殊情况,我要做的是:检索两个数字列表,对每个列表进行平均,然后减去两个平均值。为了避免像3.333这样的平均值,我在结果中使用
.toFixed(3)

下面是它的外观:

// I found this function somewhere on Stackoverflow
Array.prototype.average = function() {
  if(this.length == 0){
    return 0;
  }
  else{
    return this.reduce(function (p, c) {
      return p + c;
    }) / this.length;
  }
};

sumHigh = [ 10.965, 10.889, 10.659, 10.69, 10.599 ]
sumLow = [ 4.807, 3.065, 2.668, 2.906, 3.606, 4.074, 4.153 ]

// Ok normal
console.log(sumHigh.average()) // 10.760399999999999
console.log(sumLow.average()) // 3.6112857142857138

// Ok normal
console.log(sumHigh.average().toFixed(3)) // "10.760"  Does the ".." has anything to do with my problem ?
console.log(sumLow.average().toFixed(3)) // "3.611"

// So here I have my two average values with no more than 3 numbers after the comma but it is not taken into account when substracting these two numbers...

// Not Ok, why 10.760 - 3.611 = 7.148999999999999 ?
console.log(sumHigh.average().toFixed(3) - sumLow.average().toFixed(3)) // 7.148999999999999
console.log(parseFloat(sumHigh.average().toFixed(3)) - parseFloat(sumLow.average().toFixed(3))) // 7.148999999999999

// Just as an example, this is working
console.log(parseFloat(sumHigh.average().toFixed(3)) + parseFloat(sumLow.average().toFixed(3))) // 14.371
console.log(parseFloat(sumHigh.average()) + parseFloat(sumLow.average())) // 14.371685714285713
有人能解释一下这种行为吗? 为什么减法不起作用而加法起作用


好的,我知道我可以用以下方法解决我的问题:

console.log((sumHigh.average() - sumLow.average()).toFixed(3)) // "7.149"
但这并不能解释这种行为


谢谢

您意识到您正在删除字符串吗?当您完成计算时,您应该使用太固定了。我在我的一个减法示例中使用了
parseFloat