Decimals to 2 places for money in Python 3

后端 未结 5 939
伪装坚强ぢ
伪装坚强ぢ 2020-12-15 05:26

How do I get my decimals to stay at 2 places for representing money using the decimal module?

I\'ve setting the precision, and damn near everything else

5条回答
  •  长情又很酷
    2020-12-15 06:02

    The accepted answer is mostly correct, except for the constant to use for the rounding operation. You should use ROUND_HALF_UP instead of ROUND_05UP for currency operations. According to the docs:

    decimal.ROUND_HALF_UP

        Round to nearest with ties going away from zero.

    decimal.ROUND_05UP

        Round away from zero if last digit after rounding towards zero would have been 0 or 5; otherwise round towards zero.

    Using ROUND_05UP would only round up (for positive numbers) if the number in the hundredths place was a 5 or 0, which isn't correct for currency math.

    Here are some examples:

    >>> from decimal import Decimal, ROUND_05UP, ROUND_HALF_UP
    >>> cents = Decimal('0.01')
    >>> Decimal('1.995').quantize(cents, ROUND_HALF_UP)
    Decimal('2.00')  # Correct
    >>> Decimal('1.995').quantize(cents, ROUND_05UP)
    Decimal('1.99')  # Incorrect
    >>> Decimal('1.001').quantize(cents, ROUND_HALF_UP)
    Decimal('1.00')  # Correct
    >>> Decimal('1.001').quantize(cents, ROUND_05UP)
    Decimal('1.01')  # Incorrect
    

提交回复
热议问题