Decimals to 2 places for money in Python 3

Musaab picture Musaab · Sep 26, 2011 · Viewed 17.7k times · Source

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, and met with failure.

Answer

patrys picture patrys · Sep 26, 2011

When working with money you usually want to limit precision as late as possible so things like multiplication don't aggregate rounding errors. In python 2 and 3 you can .quantize() a Decimal to any precision you want:

unit_price = decimal.Decimal('8.0107')
quantity = decimal.Decimal('0.056')
price = unit_price * quantity
cents = decimal.Decimal('.01')
money = price.quantize(cents, decimal.ROUND_HALF_UP)