Floating point error

I’ve ended programming and i have 5/6 objectives completed.
The last one didn’t work because i get 0.03 pennys instead of 0.04 because of the floating point error.
How can I fix it ?

function checkCashRegister(price, cash, cid) {
const currency = [
  ["ONE HUNDRED", 100],
  ["TWENTY", 20],
  ["TEN", 10],
  ["FIVE", 5],
  ["ONE", 1],
  ["QUARTER", 0.25],
  ["DIME", 0.1],
  ["NICKEL", 0.05],
  ["PENNY", 0.01], 
];  
//Objeto que se devuelve
let returnObj = {status: "", change: []};
//Cambio a devolver
let change = cash-price;
console.log(change);
//Comprueba que hay dinero suficiente
let availableChange = cid.reduce((a,b) => {
  return a + b[1];  
},0).toFixed(2);
console.log(availableChange);
//Si tienes justo lo devuelves y se cierra
if(availableChange == change){
  returnObj.status = "CLOSED";
  returnObj.change = cid;
  return returnObj;
} 
//Si no llega hay dinero
else if(availableChange < change){
  returnObj.status = "INSUFFICIENT_FUNDS";
  return returnObj;
} 
//Comprueba si se puede devolver
else{
  cid.reverse().map((item,pos)=>{
    let cont = 0;
    while(1){
      if(currency[pos][1] <= change &&
      change - currency[pos][1] >= 0){
        if(cid[pos][1]/currency[pos][1]>=1){
          cont++;
          cid[pos][1] -= currency[pos][1];
          change -= currency[pos][1];
        } else{
          break;
        }
      } else {
        break;
      }
    }
    if (cont!=0){
      returnObj.change.push([currency[pos][0],cont*currency[pos][1]]);
    }
  });
}
if(returnObj.change!=[]){
  returnObj.status = "OPEN";
}
if(change != 0){
  returnObj.status = "INSUFFICIENT_FUNDS";
  returnObj.change = [];
}
return returnObj;
}

console.log(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/96.0.4664.45 Safari/537.36

Challenge: Cash Register

Link to the challenge:

There are different solutions. One would be to convert and compute everything as integer cents.

I’ve solved the problem by using toFixed(2) but it’s like a little fix, not a solution.
That could be a great idea too, and then add both with join(".").

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