A rounding and distribution problem

24 Views Asked by At

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.