什么类用于代表货币?

时间:2009-09-10 17:52:05

标签: python currency rounding-error arbitrary-precision precision

为了避免出现大多数舍入错误,我应该使用什么类来代表金钱呢?

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

我可以使用支持货币转换的现有Money类吗?

我应该避免任何陷阱?

6 个答案:

答案 0 :(得分:13)

切勿使用浮点数来代表金钱。浮动数字不能准确表示十进制表示法中的数字。你会以复合舍入错误的噩梦结束,并且无法在货币之间可靠地转换。请参阅Martin Fowler's short essay on the subject

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

我不认为python-money是一个不错的选择,因为它没有维护很长一段时间,而且它的源代码有一些奇怪且无用的代码,交换货币就完全被打破了。

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

答案 1 :(得分:11)

只需使用decimal

答案 2 :(得分:7)

我假设您在谈论Python。 http://code.google.com/p/python-money/ “在Python中使用货币和货币的原语” - 标题是自我解释的:)

答案 3 :(得分:4)

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

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

答案 4 :(得分:4)

您可以查看此库:python-money。由于我没有经验,我无法评论其有用性。

你可以用来处理整数货币的'技巧':

  • 乘以100 /除以100(例如$ 100,25 - > 10025)以'美分'表示

答案 5 :(得分:1)

简单,轻量且可扩展的想法:

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)

你可以:

  • 仅在您的应用程序中实现您需要的内容。
  • 随着你的成长扩展它。
  • 根据需要更改内部表示和实施。