Skip to content

currency calculation using decimal in Python

homepage-banner

real life example

rate = 1.45
seconds = 3*60 + 42
cost = rate* seconds / 60
print(cost)
5.364999999999999

After round up, result is 5.36, less 0.01 than real life example

use demical

from decimal import Decimal
rate = Decimal('1.45')
seconds = Decimal(3*60 + 42)
cost = rate * seconds / Decimal(60)
print(cost)
5.365

result is 5.37 after round up

auto roundup

from decimal import ROUND_UP
cost = Decimal('5.365')
rounded = cost.quantize(Decimal('0.01'),rounding=ROUND_UP)
print(f'Rounded {cost} to {rounded}')

small number roundup

rate = Decimal('0.05')
seconds = Decimal('5')
small_cost = rate * seconds / Decimal(60)
print(small_cost)
rounded = small_cost.quantize(Decimal('0.01'),rounding=ROUND_UP)
print(f'Rounded {small_cost} to {rounded}')
Leave a message