使用减法的Javascript toFixed行为

时间:2017-02-21 22:06:01

标签: javascript rounding tofixed

我在我的应用程序中操作了很多数字。对于这种特殊情况,这就是我所做的:我检索两个数字列表,我对每个列表做一个平均值,然后我减去两个平均值。为避免平均值如3.333333333333,我在结果上使用.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"

但这并不能解释这种行为。

由于

0 个答案:

没有答案