$ ./guess_the_languageProblem Solving — fix the bug
Problem Solving — fix the bug · hard · #113

Which fix removes the subtle bug?

const total = items.reduce((sum, i) => sum + i.price, 0);
const cents = total * 100;
save(Math.round(cents));
  1. Round each price to cents before summing
  2. Round each price to cents after summing
  3. Store the total as a fixed-2 string value
  4. Replace Math.round with Math.floor
Summing binary floats accumulates error; convert to integer cents first and add those.
Play Problem Solving ▸