39

我应该使用什么类来表示货币以避免大多数舍入错误?

我应该使用Decimal,还是简单的内置number

有没有Money我可以使用的支持货币转换的现有课程?

我应该避免的任何陷阱?

4

6 回答 6

29

永远不要使用浮点数来表示金钱。浮点数不能准确地表示十进制数。您将以复合舍入错误的噩梦结束,并且无法可靠地在货币之间进行转换。请参阅Martin Fowler 关于该主题的短文

如果您决定编写自己的类,我建议将其基于十进制数据类型。

我不认为 python-money 是一个好的选择,因为它已经有很长一段时间没有维护了,而且它的源代码有一些奇怪和无用的代码,而且兑换货币简直就是坏掉了。

尝试py-moneyed。这是对 python-money 的改进。

于 2012-07-23T21:25:53.623 回答
15

只需使用小数

于 2009-09-11T02:20:28.043 回答
9

http://code.google.com/p/python-money/ “在 Python 中处理货币和货币的原语” - 标题不言自明:)

于 2009-09-10T18:01:25.640 回答
5

您可能对QuantLib与金融合作感兴趣。

它内置了用于处理货币类型的类,并声称已经进行了 4 年的积极开发。

于 2009-09-10T17:55:20.710 回答
5

你可以看看这个库:python-money。由于我没有使用它的经验,我无法评论它的有用性。

您可以用来将货币作为整数处理的“技巧”:

  • 乘以 100 / 除以 100(例如 $100,25 -> 10025)以“美分”表示
于 2009-09-10T17:59:53.977 回答
2

简单、轻量级但可扩展的想法:

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)

你可以:

  • 仅在应用程序中实现您需要的内容。
  • 随着你的成长扩展它。
  • 根据需要更改内部表示和实施。
于 2013-07-30T07:50:53.883 回答