currency calculation using decimal in Python
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}')
Disclaimer
- License under
CC BY-NC 4.0
- Copyright issue feedback
me#imzye.me
, replace # with @ - Not all the commands and scripts are tested in production environment, use at your own risk
- No privacy information is collected here