Hey everyone!
I’m working on the exact-change exercise. I’ve got a couple of tests passing, however when running my solution against the following test:
checkCashRegister(
3.26,
100.00,
[
["PENNY", 1.01],
["NICKEL", 2.05],
["DIME", 3.10],
["QUARTER", 4.25],
["ONE", 90.00],
["FIVE", 55.00],
["TEN", 20.00],
["TWENTY", 60.00],
["ONE HUNDRED", 100.00]
]
);
for which the expected result is:
[
["TWENTY", 60.00],
["TEN", 20.00],
["FIVE", 15.00],
["ONE", 1.00],
["QUARTER", 0.50],
["DIME", 0.20],
["PENNY", 0.04]
]
or as a number: 96.74
I encounter some funny behaviour which makes the test fail and my result is one penny short of a correct answer for the test to pass.
My solution calculates the change due (in this case 96.74), then uses reduce to produce an array of the change. During the reduce code I subtract each unit put in the change array from a changeDue
variable to keep track of how much more I need to give until it reaches 0. When outputting this changeDue
variable to the console I get the following…
changeDue 96.74 // -20
changeDue 76.74 // -20, all okay
changeDue 56.739999999999995 // -20, what happened here?!
changeDue 36.739999999999995 // -20, seems to have subtracted 20 from the last number okay?
changeDue 26.739999999999995
changeDue 16.739999999999995
changeDue 11.739999999999995
changeDue 6.739999999999995
changeDue 1.7399999999999949
changeDue 0.7399999999999949
changeDue 0.4899999999999949
changeDue 0.23999999999999488
changeDue 0.13999999999999488
changeDue 0.03999999999999487
changeDue 0.02999999999999487
changeDue 0.01999999999999487
changeDue 0.009999999999994869
Now I’m guessing it’s some issue to do with subtracting an integer/whole-number from a floating-point number and a quick google just now shows it can probably be solved by converting the floating point to integer (see http://stackoverflow.com/questions/10713878/decimal-subtraction-problems-in-javascript), but I’d like to know:
- Why this only happened on the second subtraction and not the first?
- The best way to tackle this issue (is it simply floating point * 10 then divide result by 10)?
Thanks in advance to anyone who can help!