Cash Register off by a penny

Tell us what’s happening:
My Array (newArr) is off by one penny. i have a while loop that should keep going till x is equal to change. It goes ill 96.73 and not 96.74. i am trying to solve for the the 3rd test. ill add name values and drop the zero once in can find out why im off a penny. is my approach wrong?

Your code so far


function checkCashRegister(price, cash, cid) {
const result = {
status : ["INSUFFICIENT_FUNDS","CLOSED","OPEN"],
change : []
}
//Get Change from purchase
let change = cash - price;
//get total of CID values
var d = cid.map((ci)=>{return ci[1]})
var cidTotal =  d.reduce((acc, xx)=>{ return (acc + xx) },0)
cidTotal = Math.round(cidTotal * 100) / 100;
//Get total number of each coin CID
let key = {"PENNY" : .01, "NICKEL" : .05, "DIME" : .10, "QUARTER" : .25, "ONE" : 1, "FIVE" : 5, "TEN" : 10, "TWENTY" : 20, "ONE HUNDRED": 100};
let keyValues = Object.values(key).reverse();

//check for INSUFFICENT 
if (cidTotal < change){
result.status = "INSUFFICIENT_FUNDS";
return result;
} 
//Check for CLOSED status
if (cidTotal == change){
result.status = "CLOSED"
result.change = cid;
return result;
}
//Check for OPEN status
else{
//Filter key objects to pull value closet to change var and assing to result
  let newArr = []
  cid.reverse()
let loopKey = keyValues.filter(fi => fi < change)
let nums = cid.filter(ci => ci[1] <= change)
  .map(ma => (Number(ma[1].toFixed(2))))
let x = 0
let i = 0
while(x <= change){
console.log(x)
  if (x + nums[i] > change){
    while (x + nums[i] > change){
      nums[i] -= loopKey[i] 
    }
      nums[i] = Math.round(nums[i] * 100) / 100
  }
 newArr.push(nums[i])
x += nums[i]
i++
}
console.log(newArr)

  result.status = "OPEN";
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.113 Safari/537.36.

Challenge: Cash Register

Link to the challenge:

Floating point numbers are subject to roundoff errors. I recommend instead using an integer number of cents (priceCents = price * 100) to prevent roundoff.

1 Like