0

I have the following numerical array:

var numberArray: number[] = [2.15, 0.72, 2.15, 0.72, 0.72];

where the sum of the values is 6.46. However, if I also run:

var Total = numberArray.reduce(function(a, b) {return a + b;});

I always get 6.459999999999999.

I have a numerical array with about 1000 values and when I try and get the total of these my numbers are way off and I think this is the reason. How can I get this to aggregate properly?

Patricio Vargas
  • 5,236
  • 11
  • 49
  • 100
Woody
  • 1,677
  • 7
  • 26
  • 32
  • 1
    What do you mean by the total being "way off"? Is it off by `0.0000000000001`? – ConnorsFan Sep 28 '18 at 00:48
  • `var Total = numberArray.reduce(function(a, b) { return a + b; }, 0).toFixed(2);`? Perhaps! – Ele Sep 28 '18 at 00:50
  • @ConnorsFan "I have a numerical array with about 1000 values and when I try and get the total of these my numbers are way off." The error gets larger the more numbers I have any my array. – Woody Sep 28 '18 at 00:55

1 Answers1

2

The toFixed() method formats a number using fixed-point notation.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

const numberArray: number[] = [2.15, 0.72, 2.15, 0.72, 0.72];
const Total = numberArray.reduce((a, b) => {return a + b;});
console.log(Total.toFixed(2));
Patricio Vargas
  • 5,236
  • 11
  • 49
  • 100