var money = [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00], ["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]];
var total = 0;
for (var i = 0; i < money.length; i++) {
total += money[i][1];
}
console.log(total);
I don’t really understand why the var total ends up being 335.40999999999997 instead of a number rounded up to two decimals.I know that I can round the number with Math.round or make it round to as many decimals that I want. I solved the challenge already but this remained a mystery. I had the same problem some time ago when I was adding some other numbers in a similar way.What exactly happens here?
It’s because floating point arithmetic in JavaScript is not accurate all the time, it has to do with the fact that numbers in JavaScript are always stored as double precision floating point (64 bit)
if you console.log inside your loop you can see the culprit is 1.01
If not just be careful when dealing with floating points , and always round to exactly what you need especially if precision is of paramount importance.