Help! Why the sum is not correct?

const cid = [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]];

  let sum = 0;
  for (let i = 0; i < cid.length; i++) {
    sum += cid[i][1];

why it gives 335.40999999999997, not 335.41???

try Number.toFixed()


Number(123.4567).toFixed(2) // returns 123.46
1 Like

but why did this happen?

Check this video, it can help explain:

1 Like

It’s a floating point number, and floating point numbers are an approximation.

It’s how computers generally approximate decimal expansion (eg the fractional number ½ can be represented as 0.5).

Computers have a limited number of digits they can represent, so you often get rounding, but they’re basically the same number – 355.409* (that’s 9 recurring) is exactly the same as 355.41 if you had an infinite number of 9s after the 0. You do not have an infinite number though, so you often get very slight rounding errors.

Use integers if you want output that looks more sensible to you: so this challenge uses cents, so multiply all numbers by 100 first to get integers (1 instead of 0.01, 2000 instead of 20). Then divide by 100 as the last thing you do to get values in $.

That video @ilenia posted is very good, definitely watch that.

Edit: also I’ve seen this recommended quite a lot for a number of years now, its seems quite good but I’ve never really dug into it because stuff discussing the intricacies of floating point makes my eyes glaze over, maybe you will not find it so boring!

1 Like