Cash Register one test fails

Tell us what’s happening:

when passing(3.26, 100) , the test return all values correctly but PENNY returned 0.3 but it should return 0.4 How?

Your code so far


var denom = [
  { name: 'ONE HUNDRED', val: 100.00},
  { name: 'TWENTY', val: 20.00},
  { name: 'TEN', val: 10.00},
  { name: 'FIVE', val: 5.00},
  { name: 'ONE', val: 1.00},
  { name: 'QUARTER', val: 0.25},
  { name: 'DIME', val: 0.10},
  { name: 'NICKEL', val: 0.05},
  { name: 'PENNY', val: 0.01}
]
// console.log( checkCashRegister(3.26,100, [["PENNY", 1.01], 
// 3.26, 100 = 96.74
function checkCashRegister(price, paid, cid) {
	let objReturn = {status: "INSUFFICIENT_FUNDS", change: []}
	let totalCash = cid.reduce((acc, value) => {
		return value[1] + acc
	},0)
	let change = paid - price // 0.5
	if(totalCash < change) {
		return objReturn
	}else if (totalCash == change) {
		objReturn.status = 'CLOSED'
		objReturn.change = cid
		return objReturn
	}
  // concat the object with its amount present and value 
  // e.g { name: 'PENNY', val: 0.01, amount : 1.01 }
	let arrayWithValue = denom.map((value, index) => {
		value.amount = cid[cid.length - 1 -index][1]
		return value
	})
	// console.log(arrayWithValue);
	let temp = []
	arrayWithValue.forEach(value => {
		// console.log(value);
		if(change >= value.val){
			let answ = 0
			while(value.amount >= 0 && change >= value.val) {
				change -= value.val
				value.amount -= value.val
				answ += value.val
			}
			temp.push([value.name,answ])
		}
	})
  if(change !=0) {
			return {status: "INSUFFICIENT_FUNDS", change: []}
		}
	objReturn.status = 'OPEN'
	objReturn.change = temp
	return objReturn
}

// Example cash-in-drawer array:
// [["PENNY", 1.01],
// ["NICKEL", 2.05],
// ["DIME", 3.1],
// ["QUARTER", 4.25],
// ["ONE", 90],
// ["FIVE", 55],
// ["TEN", 20],
// ["TWENTY", 60],
// ["ONE HUNDRED", 100]]

checkCashRegister(19.5, 20, [["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 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/cash-register/

I guess it’s because JS doesn’t do very accurate calculations with decimals (for example, 0.1 + 0.2 doesn’t return 0.3, but something like 0.300000004). Because of this, after third calculation with the pennies, the change left seems to be 0.009999999999994869 (just a little bit less than 0.01) so it won’t go for the fourth round.

So the inaccuracy of the decimal calculation is something you need to find a way around in your code.

1 Like