什么类用于代表货币?

Est*_*ber 25 python precision currency rounding-error arbitrary-precision

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

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

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

我应该避免哪些陷阱?

Thi*_*ves 15

切勿使用浮点数来代表金钱.浮动数字不能准确表示十进制表示法中的数字.你会以复合舍入错误的噩梦结束,并且无法在货币之间可靠地转换.请参阅Martin Fowler关于这一主题的短文.

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

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

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

  • 小数是基于浮点的,我很好奇它如何解决这个问题 (3认同)
  • Python 十进制文档的第一部分描述了它如何修复或解决浮点问题:https://docs.python.org/3/library/decimal.html 希望有所帮助。 (3认同)

S.L*_*ott 11

只需使用小数.

  • 由于十进制处理精度的方式,因此不适合使用。假设您要处理的金额少于100亿美元,且精度为0.01美元,那么您告诉十进制库您的数字将不超过12位数字。现在您有两个问题:您的代码无法处理恶性通货膨胀;$ 0.01将显示为'0.010000000000'。 (3认同)

juc*_*bee 8

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 :)

  • 这就是标签的用途:) (2认同)
  • 查看http://code.google.com/p/python-money/source/browse/trunk/money/Money.py,我发现它们确实使用`Decimal`进行内部表示:) (2认同)

Jon*_*n W 5

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

它内置了用于处理货币类型的类,并声明了 4 年的积极开发。


Chr*_*heD 5

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

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

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

  • 许多会计系统跟踪事物的精确度远远超过分位数。 (8认同)

and*_*uso 5

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

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)

你可以:

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