Skip to content

Instantly share code, notes, and snippets.

@phrz
Created November 12, 2023 19:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phrz/874b2923c1c5e7eacd9d9fa2582af011 to your computer and use it in GitHub Desktop.
Save phrz/874b2923c1c5e7eacd9d9fa2582af011 to your computer and use it in GitHub Desktop.
Divide a dollar amount roughly evenly amongst `n` parties accounting for amounts that cannot be divided evenly.
import decimal
Decimal = decimal.Decimal
def split_amount(dec, n):
splits = [(dec/Decimal(n)).quantize(Decimal('0.01'), decimal.ROUND_DOWN)]*n
while (error_cents := int((dec - sum(splits)) * 100)) != 0:
for i in range(error_cents):
splits[i] += Decimal('0.01')
if not dec == sum(splits):
print('WARNING: SPLIT_AMOUNT DID NOT ADD UP TO TOTAL')
print(splits,dec)
return splits
print(split_amount(Decimal('100'),1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment