代码之家  ›  专栏  ›  技术社区  ›  Esteban Küber

用什么类别来表示金钱?

  •  19
  • Esteban Küber  · 技术社区  · 15 年前

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

    我应该用吗? Decimal 或简单的内置 number ?

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

    我应该避免任何陷阱吗?

    6 回复  |  直到 11 年前
        1
  •  7
  •   juckobee    15 年前

    我猜你在说蟒蛇。 http://code.google.com/p/python-money/ “在python中使用货币和货币的原语”-标题不言自明:)

        2
  •  12
  •   Thiago Chaves    12 年前

    不要使用浮点数来表示货币。浮点数不能准确地用十进制表示数字。你将以复合舍入错误的噩梦结束,并且无法在货币之间可靠地转换。见 Martin Fowler's short essay on the subject .

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

    我不认为python money是一个很好的选择,因为它的维护时间不长,它的源代码有一些奇怪的、无用的代码,而交换货币只是被破坏了。

    尝试 py-moneyed . 这是对python金钱的改进。

        3
  •  11
  •   S.Lott    15 年前

    只是使用 decimal .

        4
  •  4
  •   Jon W    15 年前

    你可能对 QuantLib 与财务合作。

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

        5
  •  4
  •   ChristopheD    15 年前

    你可以看看这个图书馆: python-money . 因为我没有这方面的经验,我不能评论它的实用性。

    您可以使用一个“技巧”将货币作为整数进行处理:

    • 乘以100/除以100(例如$100,25->10025),表示为“美分”
        6
  •  1
  •   andruso Sungam    11 年前

    简单,重量轻,但可扩展的理念:

    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)
    

    你可以:

    • 只实现应用程序中需要的内容。
    • 随成长而延伸。
    • 根据需要更改内部表示和实现。