2

I want to divide a given dollar amount into 3 parts based on the weightage shown below.

amount = 2220
multiply = [0.6217, 0.1621, 0.2162] # sums up to 1

part_a = amount * multiply[0] # 1380.174
part_b = amount * multiply[1] # 479.964
part_c = amount * multiply[2] # 359.86199999999997

total = part_a + part_b + part_c
print(total) # 2220.0

The sum of part_a, part_b, part_c adds up to 2220. However, the issue arises when I tried to round it up into 2 decmial place.

part_a = round(amount * multiply[0], 2) # 1380.17
part_b = round(amount * multiply[1], 2) # 479.96
part_c = round(amount * multiply[2], 2) # 359.86

total = part_a + part_b + part_c
print(total) # 2219.9900000000002

Why is it that the individual value for part_a, part_b, part_c is in 2 decimal place but the total becomes 2219.9900000000002?

What would be the best way to calculate the results such that the part a, b, and c would be in 2 decimal places and the summation of different parts would add up to the initial amount which is 2200?

Edwin
  • 461
  • 1
  • 5
  • 14

1 Answers1

1

Floating point arithmetic is a problem for all programming languages.

I've seen most people multiple numbers by 100, to make the decimal values integers. Then round to the nearest integer when doing your computations. Before they are presented to user (or when appropriate) convert them back to decimals with 2 digits of precision.

Stuart
  • 465
  • 3
  • 6