Format Python Decimal object to a specified precision

前端 未结 2 1141
难免孤独
难免孤独 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.

提交回复
热议问题