Decimal provides decimal floating-point arithmetic for situations where ordinary floats are potentially inaccurate, especially calculations involving money. section 1.16 section 8.2
Adding user-entered decimals
Convert the input strings directly to Decimal instances, add them, and preserve the expected result when users enter values such as 0.1 and 0.2. Keep values as Decimal during arithmetic and convert to float only at the last possible moment. section 1.16 section 8.2
from decimal import Decimal
rates = {
'Chico': Decimal('0.5'),
'Groucho': Decimal('0.7'),
'Harpo': Decimal('0.5'),
'Zeppo': Decimal('0.4')
}
def time_percentage(hour):
return hour / Decimal('24.0')
def calculate_tax(amount, state, hour):
return float(amount + (amount * rates[state] * time_percentage(hour)))
A tax calculation keeps rates and time percentages as Decimal values, then converts the final result to float. section 8.2




