"""Original illustrative rounding policy; not tax or accounting rules."""
from decimal import Decimal, ROUND_HALF_UP, ROUND_FLOOR
CENT=Decimal('0.01')
VALUES={k:Decimal('0.05')*Decimal('0.90') for k in ('A','B','C')}
def money(v):return v.quantize(CENT,rounding=ROUND_HALF_UP)
line_total=sum(money(v) for v in VALUES.values())
invoice_total=money(sum(VALUES.values()))
target_pence=int(invoice_total*100)
base={k:int((v*100).to_integral_value(rounding=ROUND_FLOOR)) for k,v in VALUES.items()}
remaining=target_pence-sum(base.values())
rank=sorted(VALUES,key=lambda k:(-(VALUES[k]*100-base[k]),k))
allocated=base.copy()
for k in rank[:remaining]:allocated[k]+=1
if __name__=='__main__':
 assert line_total==Decimal('0.15')
 assert invoice_total==Decimal('0.14')
 assert line_total-invoice_total==CENT
 assert allocated=={'A':5,'B':5,'C':4}
 assert sum(allocated.values())==target_pence==14
 assert allocated['C']==4 and int(money(VALUES['C'])*100)==5
 print('Exact lines:',VALUES)
 print('Rounded lines total:',line_total,'rounded invoice total:',invoice_total)
 print('Allocated recorded pence:',allocated)
 print('Refunding recorded C:4p; recomputing independent half-up C:5p')
 print('6/6 assertions passed; illustrative arithmetic only.')
