Let me suggest that you use decimal arithmetic using class decimal.Decimal
. Even if you need the final result to be an integer value, using decimal arithmetic for intermediate calculations will provide greater accuracy. For the example you provided, what you are doing in the second set of calculations work well enough but only because of the specific values used. What if price_in_wei
were instead 1000000000000000001? Your calculation would yield 9.95e+17 or, if converted to an int, 99500000000000000:
>>> price_in_wei
1000000000000000001
>>> price_with_fee = price_in_wei*995/1000
>>> price_with_fee
9.95e+17
>>> int(price_with_fee)
995000000000000000
But decimal arithmetic provides greater precision:
>>> from decimal import Decimal
>>> price_with_fee = Decimal(price_in_wei) * 995 / 1000
>>> price_with_fee
Decimal('995000000000000000.995')
>>> price_with_fee = int(price_with_fee.quantize(Decimal(1))) # round to an integer and convert to int
>>> price_with_fee
995000000000000001
But let's say your currency were US Dollars, which supports two places of precision following the decimal point (cents). If you want that precision, you should work exclusively with decimal arithmetic. For example:
>>> from decimal import Decimal, ROUND_HALF_UP
>>> price_in_wei = Decimal('1000000000000000003')
>>> price_with_fee = (price_in_wei * 995 / 1000).quantize(Decimal('1.00'), decimal.ROUND_HALF_UP) # round to two places
>>> price_with_fee
Decimal('995000000000000002.99')