Cash Register: Off by 1 penny. Help plz

Tell us what’s happening:

My code is passing the tests, but I noticed it doesn’t work 100% accurately. There appears to be a rounding error when it comes to pennies. For example, if you input “1” for “cash” and “.23” for price, I’m getting 3 pennies when I should only get 2.

On line 155 I added Math.ceil which I thought would solve the rounding issue, but it’s not the universal fix I was looking for.

Insight would be greatly appreciated. Codepen link below.

Your code so far

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36.

Challenge: Cash Register

Link to the challenge:

1 Like

Floating point numbers always have rounding. I recommend keeping track of an integer number of cents instead (priceCents = 100 * price).

1 Like

Thanks, I just learned about the floating point number issue in Javascript. I went ahead and converted all instances of decimals to integers using this formula (cash * 100 - price * 100) / 100.

I’m still seeing an issue however, on line 79 I did a console.log and am seeing that the first iteration of the loop works, but the decimals reappear on subsequent loops, do you happen to know why this is happening? Pen below:

Nevermind, I got it working. Thank for your help!

1 Like