PawelRoman
PawelRoman

Reputation: 6262

Python: splitting money value (represented as Decimal with 2 significant places) into X equal parts

I have the following problem: I have a decimal value representing money, with 2 decimal places. I need to split it into X equal parts also represented as decimals with 2 decimal places.

Example 1: splitting 1.04 (1 dollar and 4 cents) into 3 equal parts should give: 0.35, 0.35, 0.34

Example 2: splitting 0.01 (1 cent) into 3 equal parts should give: 0.01, 0.00, 0.00

and so on.

Upvotes: 1

Views: 593

Answers (2)

Sushil
Sushil

Reputation: 5531

This should help you:

money = 1.04
n = 3
lst = []
divided = round(money/n,2)
for x in range(n):
    if sum(lst) == money:
        lst.append(0.0)
    elif x == n-1:
        lst.append(round(money-sum(lst),2))
    else:
        lst.append(divided)

lst.sort(reverse=True)
print(lst)

Output:

[0.35, 0.35, 0.34]

Upvotes: 1

Laurent H.
Laurent H.

Reputation: 6526

I suggest you using the integer division to find the result. Here is an example, that I find easily readable:

def func(money,n):
    q = round(((money * 100) // n) / 100, 2)  # quotient
    r = int(money * 100 % n)                  # remainder
    q1 = round(q + 0.01, 2)                   # quotient + 0.01
    result = [q1] * r + [q] * (n-r)
    return result

print(func(1.04,3))  # [0.35, 0.35, 0.34]
print(func(0.01,3))  # [0.01, 0.0, 0.0]

Upvotes: 2

Related Questions