Strange problem when subtracting (CashRegister)

When I am subtracting a number from another number it is all of a sudden becoming a different number.
For example, when I am doing the following equation:
98.74-60 (rtn-=20*mult);
The result is becoming something like: 38.739999995
Tell us what’s happening:
Describe your issue in detail here.

Your code so far


function checkCashRegister(price, cash, cid) {

}

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; Fedora; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0

Challenge: Cash Register

Link to the challenge:

This is known as floating point error, and is a thing you will have to deal with in all programming languages. The issue comes from the way computer stores decimal numbers, and that problem becomes real when you expect equations like 0.1*0.2 to equal 0.02 but in reality it’ll probably give something like 0.02000000004.

How it is dealt with is on a case by case basis.

Most of the time it won’t matter to the math your program needs to do.

Here since you only ever need to be precise to the hundredth place, you can multiply everything by 100 and round to integer, giving you value in cents instead of dollars to work with.

There are also libraries that has accurate floating point calculations built in, but that’s usually unnecessary.

2 Likes

Thanks a lot.
This is how I ultimately solved the issue and submitted the project.
But felt like I was cheating.
Looks like, not this is actually a bug.
This is really strange to have such a bug though :slight_smile:

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