Est*_*ber 25 python precision currency rounding-error arbitrary-precision
我应该使用什么类来表示金钱以避免大多数舍入错误?
我应该使用Decimal
还是简单的内置number
?
Money
我可以使用现有的支持货币转换的类吗?
我应该避免哪些陷阱?
Thi*_*ves 15
切勿使用浮点数来代表金钱.浮动数字不能准确表示十进制表示法中的数字.你会以复合舍入错误的噩梦结束,并且无法在货币之间可靠地转换.请参阅Martin Fowler关于这一主题的短文.
如果您决定编写自己的类,我建议将其基于十进制数据类型.
我不认为python-money是一个不错的选择,因为它没有维护很长一段时间,它的源代码有一些奇怪和无用的代码,交换货币简直就是打破了.
尝试py-moneyed.这是对python-money的改进.
I assume that you talking about Python. http://code.google.com/p/python-money/ "Primitives for working with money and currencies in Python" - the title is self explanatory :)
你可以看看这个库:python-money。由于我没有使用它的经验,我无法评论它的实用性。
您可以用来将货币作为整数处理的“技巧”:
简单、轻量但可扩展的想法:
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)
Run Code Online (Sandbox Code Playgroud)
你可以: