Format Python Decimal object to a specified precision

前端 未结 2 1132
难免孤独
难免孤独 2020-12-28 19:13

I\'ve spent countless hours researching, reading, testing, and ultimately confused and dismayed at Python\'s Decimal object\'s lack of the most fundamental concept: Formatti

2条回答
  •  遥遥无期
    2020-12-28 19:58

    Just use string formatting or the format() function:

    >>> for dec in decimals:
    ...    print format(dec, '7.2f')
    ... 
       0.00
      11.11
     222.22
    3333.33
    1234.57
    

    decimal.Decimal supports the same format specifications as floats do, so you can use exponent, fixed point, general, number or percentage formatting as needed.

    This is the official and pythonic method of formatting decimals; the Decimal class implements the .__format__() method to handle such formatting efficiently.

提交回复
热议问题