0

The below javascript reduce function produce wrong sum , is it?

Kindly help me to understand why?

What is the right way to get the correct sum?

const array1 = [2.01,2.01,2.01,2.01,2.01,2.01,2.01,2.01,2.01,1.91];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 2.01,2.01,2.01,2.01,2.01,2.01,2.01,2.01,2.01,1.91
console.log(array1.reduce(reducer));
   

// 5 + 2.01,2.01,2.01,2.01,2.01,2.01,2.01,2.01,2.01,1.91
console.log(array1.reduce(reducer, 5));

Result :

19.999999999999996 24.999999999999996

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

Cegone
  • 489
  • 1
  • 9
  • 23
  • 1
    [Is floating point math broken?](https://stackoverflow.com/q/588004/4642212). This has nothing whatsoever to do with `reduce`. – Sebastian Simon Aug 16 '18 at 13:34
  • I'm adding those numbers by eye and somehow I agree with the browser :) OR is it again the floating point complaint? – ibrahim tanyalcin Aug 16 '18 at 13:34
  • 2
    How is the expected output 10 and 15? – void Aug 16 '18 at 13:35
  • @Denys Séguret Can you give me the link of where the question already asked in stack overflow? – Cegone Aug 16 '18 at 13:45
  • The sum of value should 20 not 19.999999999999996. Any one help me to understand why? – Cegone Aug 16 '18 at 13:47
  • 1
    https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript or https://stackoverflow.com/q/588004/4642212 should be clear enough. If it isn't read https://www.itu.dk/~sestoft/bachelor/IEEE754_article.pdf – Denys Séguret Aug 16 '18 at 13:47

0 Answers0