# Exact Change - wrong rounding prevented me from solving the challenge

Tell us what’s happening:

Hello, I encountered a weird problem. I wrote a code that should work but it failed on test #5, falling short by one penny. The reason of the code failing was because the interpreter has some weird rounding problem on the nth place after the dot.

To test it, I just put a simple return statement at the very beginning, and here’s the output:

return cid[0][1];
// outputs 1.01 - everything is ok

return cid[0][1]-1;
// outputs 0.010000000000000009 - what?

so because of this weird problem, my change when I reach pennies is 0.039999999999994872 instead of 0.04

I actually “fixed” it by adding .toFixed(2) here and there, but is the interpreter even supposed to behave like that? Is it a bug or a feature?

Welcome to the magnificent world of floating points…

1 Like

Hah, nice, thanks!

I mean, I remember the joke:

• why did they call the new cpu Pentium and not 586?
• because when it added 100 to 486, the result was 585.99999999999

mocking this kind of inaccuracies in floating point operations, but I had no idea that 25 years later that’s still a thing.

Also I finally know why some code I’m familiar with accounts for all money sums in cents and only shifts the decimal dot after all operations are done.

Wow, thanks!! I had a similar issue. In my case 0.47 - 0.01 = 0.4599999999999999 ??? Guess it’s “normal”.
I ended up doing
Math.round( (0.47 - 0.01) * 100) / 100

1 Like