Decimals to 2 places for money in Python 3

后端 未结 5 942
伪装坚强ぢ
伪装坚强ぢ 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:00

    >>> decimal.getcontext().prec = 2
    >>> d = decimal.Decimal('2.40')
    >>> d/17
    Decimal('0.14')
    

    You just have to set the precision to 2 (the first line) and them everything will use no more than 2 decimal places

    Just for comparison:

    >>> 2.4 / 17
    0.1411764705882353
    

提交回复
热议问题