JavaScript Algorithms and Data Structures Projects: CashRegistr

Tell us what’s happening:
//SOLUTION FOR JS CASH REGISTER
I came across a rounding error when trying to complete this challenge. I get change that is less than 0.01$. I tried to get around it by rounding using num.toFixed(2) but that isn’t an accepted solution. Can you help me see where I went wrong?

  **Your code so far**

function checkCashRegister(price, cash, cid) {

//an array of currency units
var denom = [100,20,10,5,1,0.25,0.1,0.05,0.01]

//difference b/n cash and price i.e. change  
let dfc = cash-price;
console.log(dfc);
//cash in register written in array of currency units
let cidDenom = cid
.reverse()
.reduce((cdnm,itm) => {
  cdnm.push(itm[1])
  return cdnm
  },[]);

console.log(cidDenom);

//change written in array of currency units
let dfcDenom = denom
.reduce((ddnm,itm,idx)=> {
  if (parseInt(dfc/itm) > 0) {
    parseInt(dfc/itm)*denom[idx] > cidDenom[idx] ? (ddnm.push(cidDenom[idx]),dfc = dfc - cidDenom[idx]):
    (ddnm.push(parseInt(dfc/itm)*denom[idx]),dfc = dfc - (parseInt(dfc/itm))*denom[idx]);
    ;
    return ddnm;
  }
  ddnm.push(0)
  return ddnm;
},[])
.reduce((fin,itm,idx) => { //fixing a rounding error that I don't know how else to fix
  if (idx == 8 && dfc < 1) 
  {itm += dfc;
  itm = itm.toFixed(2)
  dfc = 0;}
  fin.push(itm);
  return fin;
},[]);
console.log(dfcDenom);
//subtract change from cid
cidDenom = cidDenom.reduce((cdnm,itm,idx) => {
cdnm.push(itm-dfcDenom[idx])
cid[idx][1] = cdnm[idx];
return cdnm;
},[]);

//reducing dfcDenom to the change array required
dfcDenom = dfcDenom
.reduce((dwdnm,itm,idx) => {
dwdnm.push([cid[idx][0],itm])
return dwdnm
},[])
.reverse();

//create the change var to return
var change = {status: '', change: []};
console.log(dfc)
//define conditions for change
dfc > 0 ? (change.status = 'INSUFFICENT_FUNDS' , change.change =  []) : cidDenom.every(x => x == 0) ? (change.status = 'CLOSED' , change.change =  dfcDenom) : (change.status = 'OPEN' , change.change =  dfcDenom.filter(x => x[1] !== 0));
console.log(change);
return change;
}

checkCashRegister(19.5, 20, [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]);
  **Your browser information:**

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

Challenge: Cash Register

Link to the challenge:

Floating point errors are inherent in how computers represent decimal values. I would instead work with an integer number of cents.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.