0

This is a real-life problem I'm trying to solve, I have an invoice with three items A, B, and C on it, and the total cost of this invoice is $4.98, below is how much each item costs

A $1.99

B $2.17

C $0.82

Now I need to refund a partial amount of this invoice, let's say I'm refunding 2.00 out of 4.98 and I need to refund these 3 items proportionally, therefore I will be refunding

A 2 x 1.99 / 4.98 = 0.79919678714

B 2 x 2.17 / 4.98 = 0.87148594377

C 2 x 0.82 / 4.98 = 0.32931726907

I need to round these values to 2 decimal points, therefore

A 0.80

B 0.87

C 0.33

And as you can see I'm indeed refunding $0.80 + $0.87 + $0.33 = $2.00 which is great.

However, in the same example, if I refund 2.10 instead of 2.00, there will be a problem, below is the calculation similar to the above.

A 2.1 x 1.99 / 4.98 = 0.8391566265

B 2.1 x 2.17 / 4.98 = 0.91506024096

C 2.1 x 0.82 / 4.98 = 0.34578313253

After rounding I get

A 0.84

B 0.92

C 0.35

And now the total of A+B+C that I'm refunding is 2.11 rather than 2.10 that I'm trying to refund on this invoice.

I need to use 2 decimals, how should I do rounding to avoid the above problem? The way I'm rounding is simply finding the closest number with 2 decimals, e.g. 2.784 would be rounded to 2.78 and 2.785 would be rounded to 2.79.

Arch1tect
  • 139
  • See https://en.wikipedia.org/wiki/Round-off_error You basically can't avoid it – Ross Millikan May 28 '23 at 15:11
  • That makes sense, I'm going to discuss more with other engineers next week but yeah, it doesn't seem solvable, will just have to accept the 1 cent off, unless someone manually modifies the number to make it match. – Arch1tect May 29 '23 at 01:49
  • 1
    If you think hard about how you calculate it, you can make it match. You can calculate the individual discounts and add up the new prices to get the total rather than rounding the total. That runs the risk of your customer doing the percentage on the total and seeing it out a penny (or a few cents in a more complicated case). Alternately you can compute the percentage on the total, then on the components, and apply the mismatch to a few of the components. – Ross Millikan May 29 '23 at 02:12

0 Answers0