# Weird numbers - Exact Change

``````function checkCashRegister(price, cash, cid) {
var change = cash - price;
var temp = change;
var total = 0;
var amounts = [0.01,0.05,0.1,0.25,1,5,10,20,100];
var given = [];
for(i=0;i<cid.length;i++){
total += cid[i];
cid[i] = Math.ceil(cid[i]/amounts[i]);
if(Math.floor(change/amounts[8-i])>0){
var sum = 0;
while(cid[8-i]>0 && change>0 && Math.floor(change/amounts[8-i])>0){
change -= amounts[8-i];
console.log(change);
cid[8-i]--;
sum += amounts[8-i];
}
if(sum>0){
given.push([cid[8-i],sum]);
}
}
}
if(temp>total || given.length==0){
given = "Insufficient Funds";
}else if(temp==total){
given = "Closed";
}
return given;
}
``````

In the console.log output, I get some weird numbers like 0.17999999999999972. I know it has to do with how JavaScript handles floating point numbers but I don’t know how to fix it… Any suggestions?

One way to deal with this problem is that you can convert all of your money into cents by multiplying by 100 and then at the end you will just divide by 100 to get the correct amounts.

1 Like