Why the substract works like that?

Tell us what’s happening:
Hi all. So my solution is quite complex and maybe not efficient but for now i just want to solve it. Later i will look how i can improve it.

So, my logic is to call each time the function calcMoney() to do all the required processes and after that i substract from ‘change’ variable the ‘sum’ variable. Here is what doesn’t work properly. Using the console.log() i can see that the first time i call the function, change varriable has the value 96.74 and then i substract from it the variable ‘sum’ which has the value of 60. Well, as you can see on the console, change takes the value of 36.739999 and not 36.74. Is it possible 96.74-60 to have this value? Why is that show?
Why this substract doesnt work right?

Thanks in advance!

  **Your code so far**

var changeArr = [];
var object = {
 status:'',
 change:[]
};
 
function checkCashRegister(price, cash, cid) {
var change = cash - price;
let arr = cid.reverse();
let arr2 = arr.map(item =>{
  let x = calcMoney(item,change);
  console.log(change,x);
  change -=x;
  return null;
});
object.change = changeArr;
//console.log(object);

//return change;
}

function calcMoney(item,change){
let sum = 0;
let money = {
  'PENNY':0.01,
  'NICKEL':0.05,
  'DIME':0.1,
  'QUARTER':0.25,
  'ONE':1,
  'FIVE':5,
  'TEN':10,
  'TWENTY':20,
  'ONE HUNDRED':100
};
//console.log(money[item[0]],change);
if(money[item[0]]<= change){
  while(sum + money[item[0]] <= change && sum <item[1]){
    sum = sum + money[item[0]];
    //console.log(sum,change);
  }
}
if(sum!=0){
  changeArr.push([item[0],sum]);    
}


//console.log(sum,change);

return sum;

};

//console.log(object);

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/89.0.4389.90 Safari/537.36.

Challenge: Cash Register

Link to the challenge:

the short answer is that computers have limited precision

I suggest this video on the topic

2 Likes

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