Unexpected floating problem in loop

Tell us what’s happening:
I stuck in the final project .
in the loop below initial setup I’m getting unexpected results
first iteration is fine 96.74- 20 =76.74
in second iteration 76.74-20 =56.99999999995
the same happens in console.log speratly i.e. ( console.log(76.74-20) )

Your code so far

function checkCashRegister(price, cash, cid) {
var change = cash - price;
 var register = [0.01, 0.05, 0.10, 0.25, 1.00, 5.00, 10.00, 20.00, 100.00];
  var count = []
  for(let i=0;i<register.length;i++){
  count.push(Math.floor(cid[i][1]/register[i]))
  }



console.log(change).  //here it's 96.74 
for(let i = register.length-1;i>=7;i--){
 if(  (change/register[i]) > 1 ){
     let temp = count[i]
     while(temp !== 0){
     change -= (register[i])
     console.log(change). //first iteration 76.74 ,second 56.999999999995 
     temp--
     }
}
}
console.log(96.74-20) // 76.74
//console.log(76.74 - 20) // 56.999999995
// count array[ 101, 40, 31, 17, 90, 11, 2, 3, 1 ]
//console.log('change'+change)






//console.log(' CID '+cid)




var output = { status: null, change: [] };
var total = cid.reduce((sum,current) =>  sum+current[1],0)
if(total === change)
{
 output.status = 'CLOSED'
 output.change = cid
 return output
}
if(total < change)
{
 output.status = 'INSUFFICIENT_FUNDS'
 return output
}
if(total>change)
 {
   //
 }
 return total
}
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 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.3 Safari/605.1.15.

Challenge: Cash Register

Link to the challenge:

Floating point numbers will have roundoff problems. That is just the nature of floating point operations. In this case, I recommend you use an integer number of cents in all of your calculations.

1 Like

What can you do to avoid floating point with all your values in register array?

You should

use an integer number of cents in all of your calculations.

Floating point values have roundoff. Integer values do not have rounding issues so long as you are below the maximum integer size for JavaScript.