1

I have the following code:

function checkCashRegister(price, cash, cid) {

    // Move cid into an object
    var cashReg = cid.reduce(function(prev, curr) {
        prev[curr[0]] = curr[1];
        return prev;
    }, {});

    // Total money in the register
    var regSum = Object.values(cashReg).reduce(function(a, b) {
        return a + b;
    }, 0);

    return regSum;
    // --> 335,41
}

checkCashRegister(19.50, 20.00, [
    ["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]
]);

The code itself seems to be working just fine, but for some reason when I return regSum the answer is 335,40999999999997 instead of 335,41. Why does this happen and how could I change my code so it would return the expected outcome?

Alexander Nied
  • 12,804
  • 4
  • 25
  • 45

3 Answers3

2

Just as Geuis sayed it is the number precision problem. If you expected the outcome only retains two digits after the decimal point, you can change "return regSum;" to "return Number(regSum.toFixed);". function checkCashRegister(price, cash, cid) {

// Move cid into an object
var cashReg = cid.reduce(function(prev, curr) {
    prev[curr[0]] = curr[1];
    return prev;
}, {});

// Total money in the register
var regSum = Object.values(cashReg).reduce(function(a, b) {
    return a + b;
}, 0);

return Number(regSum.toFixed(2));
// --> 335,41

}

Shawn He
  • 46
  • 1
0

You're running into the javascript number precision problem. Read more here How to deal with floating point number precision in JavaScript?

Geuis
  • 41,122
  • 56
  • 157
  • 219
0

A good way to get around this is to scale you numbers. So for $1.50, you could have 150(cents), and do your math based on that, and remember to multiply by 0.01 before displaying. I know that may be a pain, but that's javascript. If it's going to be too much of a change to do that, you could always use a library, such as decimal.js. You can read the docs here.

Jordan
  • 148
  • 1
  • 11