Simple algorithm nuance

Tell us what’s happening:

Can anyone help explain why cash-price, or 20.3 - 19.5, outputs a value of 0.8000000000000007 rather than just .8.

thanks for any help!

Your code so far

function checkCashRegister(price, cash, cid) {
var change;
return change;

checkCashRegister(19.5, 20.3, [["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/87.0.4280.88 Safari/537.36.

Challenge: Cash Register

Link to the challenge:

Floating point arithmetic always has some roundoff.

This video has a good explanation:

1 Like

Those are some excellent resources.

To put it simply, the problem is that we think of numbers in base-10 but computers store them in base-2. For example, .8 is really 4/5. 5 divides nicely into 10 so you get a decimal, .8. But 5 does not divide in 2 so you get (I think) a repeating “decimal” (“binamal”? OK, mantissa), an infinite number of digits. The computer can’t store infinite digits so it has to round it off. We do the same thing in decimal with 1/3. It can be .3 or .33 or .333, etc. We have to choose somewhere to round it off. So, if we were to convert it back to a fraction, it would be 333/1000, close but not the same thing. It is impossible to accurately represent 1/3 (and infinitely more numbers) in a finite number of decimal digits. You run into the same problem with binary numbers, but sometimes for different numbers.


Thanks for the help!