The sum code returns a very weird result with lots of number after decimal point?

This challenge: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/cash-register

I’m trying to calculate the sum of cid (the 2D array at the end of this post), and the result is very weird.

Here’s my code:


function checkCashRegister(price, cash, cid) {
let sumCid = 0;
for (let i=0; i<cid.length; i++) {
sumCid += cid[i][1];
}
console.log(sumCid)
}

checkCashRegister(19.5, 20, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]);

And the console.log prints out “335.40999999999997”. The correct result is 335.401. I don’t know what the problem is. I try using the reduce method and the outcome is exactly the same.

  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.60 Safari/537.36

Challenge: Cash Register

Link to the challenge:

You have found floating point rounding!

Personally, I prefer to handle this by doing all of the calculations in an integer number of cents.

1 Like

Thank you so much. I can feel my hair losing lol.

1 Like