Musaab Musaab - 1 year ago 56
Python Question

Decimals to 2 places for money in Python 3

How do I get my decimals to stay at 2 places for representing money using the


I've setting the precision, and damn near everything else, and met with failure.

Answer Source

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)