Format Python Decimal object to a specified precision

前端 未结 2 1128
难免孤独
难免孤独 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:50
    def d(_in, decimal_places = 3):
        ''' Convert number to Decimal and do rounding, for doing calculations
            Examples:
              46.18271  to   46.183   rounded up
              46.18749  to   46.187   rounded down
              117.34999999999999 to 117.350
             _rescale is a private function, bad practice yet works for now.
        '''
        return Decimal(_in)._rescale(-decimal_places, 'ROUND_HALF_EVEN')
    

    Edit: Again, _rescale() is not meant to be used by us regular bipeds, it works in Python 2.7, is not available in 3.4.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题