1

Given:

let rows = [
    { Amount: 190615.83 },
    { Amount: -175867.95 },
    { Amount: -14747.88 },
]
const sum = rows.reduce((runSum, v) => runSum + v.Amount, 0);
console.log(sum);

The sum should return 0 but it returns -2.3646862246096134e-11 see: https://jsfiddle.net/Brobic/q78nypuc/1/ How can I make this add correctly?

Rahul Bhobe
  • 2,815
  • 4
  • 11
  • 25
Brobic Vripiat
  • 135
  • 1
  • 8

2 Answers2

1

The behavior you see has nothing to do with array.reduce(). If you add those numbers individually, you will see similar output. This is how floating point numbers behave in most programming languages.

See code snippet below. General expectation is that both these log console logs 0.0:

console.log(190615.83 - 175867.95 - 14747.88);
console.log(1.1 + 2.2 - 3.3);

Also see more details in the this answer.

Rahul Bhobe
  • 2,815
  • 4
  • 11
  • 25
0

Thats how floating point numbers behave , you can fix it , if you know the precision, in this case it was 2:

let rows = [
    { Amount: 190615.83 },
    { Amount: -175867.95 },
    { Amount: -14747.88 },
]

const sum =  rows.map(a=>parseFloat(a.Amount)).reduce((runSum, v) => (parseFloat(runSum) + parseFloat(v)).toFixed(2));
console.log(sum);

This produces output 0.00

The parseFloat is meant for keeping dataType as float , so that the method toFixed() can be applied

Rahul Bhobe
  • 2,815
  • 4
  • 11
  • 25
Muthukumaran
  • 102
  • 3
  • 4