Cash Register - Strange FP result

Cash Register - Strange FP result
0.0 0


Hi, I’m working on the cash register challenge. Presently I am trying to ‘sort’ my change to determine how much of each denomination to give out. However in one case I am having a rather strange FP result.

My sorting looks like this:

for (let x = 0; x < cid.length; x++) { += cid[x][1];
switch(x) {
case 0:
cashInDrawer.pennies = cid[x][1] / .01;
case 1:
cashInDrawer.nickles = cid[x][1] / .05;
case 2:
cashInDrawer.dimes = cid[x][1] / .10;
case 3:
cashInDrawer.quarters = cid[x][1] / .25;
case 4:
cashInDrawer.dollars = cid[x][1] / 1;
case 5:
cashInDrawer.fives = cid[x][1] / 5;
case 6:
cashInDrawer.tens = cid[x][1] / 10;
case 7:
cashInDrawer.twentys = cid[x][1] / 20;
case 8:
cashInDrawer.hundreds = cid[x][1] / 100;

Which is all fine and dandy, however for ‘nickles’ instead of getting a count of ‘41’ I get result of 40.99999999999…


Now I get that this is floating point math… But really ? I know I could ‘force’ it with ceiling or toFixed but I just wondered is this to be expected or am I missing something here? All the other denominations work fine (produce int values).


You need to force it, you’re always going to get wierd results at some point because of floating point math. This is why in real-world systems you don’t ever work directly with currency using floating point: it can’t really handle it properly. You’re doing decimal maths with a binary system, and once you introduce division it will likely go tits up at some point (the result you’re getting isn’t technically wrong in base-2 either…).

The [partial] solution is normally to only ever use integers (so a penny should be 1, not 0.01), and then go from there, but it’s easier just to round in this case.