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
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.
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.