0

Ok, we all know javascript is terrible at math, decimals, multiplication, rounding. But I have never noticed it even is pretty terrible at adding simple decimals to a mere 1 decimal place. I would like to know why this is happening on a really trivial array sum, also rounding here is not an option to make all the troubles go away as I require accuracy. Second, can I get some recommendations on a decent math library as I'm sure the main answers will recommend one.

Heres a code pen to view javascript failing in action :) : https://codepen.io/anon/pen/jvyVzL

The code:

var sumList = [18.7, 29, 22.7, 0.3, 5.6, 17.5, 2.6, 2.6, 1]

function1 () {
  return sumList.reduce((a, b) => a + b, 0)
}

// result: 99.99999999999999
// expected: 100
MrRed
  • 677
  • 1
  • 6
  • 21
  • JavaScript represents all numbers as floating point - floating point math is *not* accurate due to rounding errors. – Chris Cousins Aug 31 '18 at 06:47
  • Floating point arithmetic is not exact in JavaScript (or most other programming languages). In fact, your answer _is_ correct, at least from the point of view of limitations of floating point. – Tim Biegeleisen Aug 31 '18 at 06:47
  • also good to read: [is-floating-point-math-broken](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Andre Albert Aug 31 '18 at 06:49
  • `Ok, we all know javascript is terrible at math` only as terrible as most other programming languages, as its the CPU doing the calculations. – Keith Aug 31 '18 at 07:03
  • ok these were kind of the answers i was expecting. some good articles linked thanks all – MrRed Aug 31 '18 at 07:06
  • Most of those fractions can't be represented exactly in FP. When you add inexact numbers, you get inexact results. – Barmar Aug 31 '18 at 07:29

0 Answers0