Python货币转换
时间: 2024-10-09 10:00:22 浏览: 54
在Python中,如果你需要进行货币转换,可以利用内置的`decimal`模块,它提供高精度的十进制数运算,非常适合金融计算。下面是一个简单的示例:
```python
from decimal import Decimal
# 定义初始汇率
base_currency = 'USD'
target_currency = 'EUR'
exchange_rate = Decimal('0.9') # 假设1美元等于0.9欧元
def convert_currency(amount, from_currency, to_currency):
if from_currency == base_currency and to_currency != target_currency:
return amount * exchange_rate
elif from_currency != base_currency and to_currency == target_currency:
return amount / exchange_rate
else:
raise ValueError("Invalid currency conversion - only between {} and {}".format(base_currency, target_currency))
# 使用示例
usd_amount = Decimal('100')
eur_amount = convert_currency(usd_amount, 'USD', 'EUR')
print(f"{usd_amount}美元等于{eur_amount}欧元")
阅读全文