Cash register project - decimal digits acting strangely

Hi! I wrote my code for the Cash register challenge, but it doesn’t pass the 3rd test. I noticed that the problem is that something strange happens when I do extraction from a floating number. If you look at the below example, change is 100-3.26 = 96.74. If I extract 10, 30, or 40 from it, the result will be 86.74, 66.74 and 56.739999999999995. Why extracting 40 or a larger number gives this distortion in the decimal digits? How can I fix this?

Your code so far


function checkCashRegister(price, cash, cid) {
var change = cash - price;
console.log(change-10, change-30, change-40);


}

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/92.0.4515.159 Safari/537.36

Challenge: Cash Register

Link to the challenge:

This is an issue in nearly every programming language I’ve used, it occurs when doing floating point math. There are a few different solutions for this, but they all boil down to three same thing: determine what kind of precision you need, and round your decimals accordingly.

Thanks for your feedback. If I use toFixed(2) it works.

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