为了避免大多数舍入误差,我应该使用什么类来表示货币?
我应该使用Decimal
还是简单的内置number
?
是否有现成的Money
类支持货币转换,可以供我使用?
有什么陷阱我应该避免吗?
为了避免大多数舍入误差,我应该使用什么类来表示货币?
我应该使用Decimal
还是简单的内置number
?
是否有现成的Money
类支持货币转换,可以供我使用?
有什么陷阱我应该避免吗?
不要使用浮点数来表示货币。浮点数不能准确地表示十进制数。你会遇到复合舍入误差的噩梦,并且无法可靠地转换货币。请参见马丁·福勒(Martin Fowler)关于此主题的简短文章。
如果你决定编写自己的类,我建议以十进制数数据类型为基础。
我认为python-money不是一个好选择,因为它已经很久没有维护了,而且它的源代码中有一些奇怪和无用的代码,兑换货币也很难使用。
试试py-moneyed。它比python-money更好。
只需使用decimal即可。
$0.01
的输出?我尝试了decimal.getcontext().prec = 12; print(decimal.Decimal('0.01'))
,但它打印出没有尾随零的0.01
。即使您确实获得了该输出,为什么不在显示之前四舍五入呢? - wjandreahttp://code.google.com/p/python-money/ 这个标题说明了它的作用:“在Python中处理货币和货币单位的基本工具”。
一个简单、轻量级但可扩展的想法:
class Money():
def __init__(self, value):
# internally use Decimal or cents as long
self._cents = long(0)
# Now parse 'value' as needed e.g. locale-specific user-entered string, cents, Money, etc.
# Decimal helps in conversion
def as_my_app_specific_protocol(self):
# some application-specific representation
def __str__(self):
# user-friendly form, locale specific if needed
# rich comparison and basic arithmetics
def __lt__(self, other):
return self._cents < Money(other)._cents
def __add__(self, other):
return Money(self._cents + Money(other)._cents)
如果您对与金融有关的it技术感兴趣,您可能会对QuantLib感兴趣。
它内置了处理货币类型的类,并且拥有4年的积极开发经验。