Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 decimal module?

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

like image 396
Musaab Avatar asked Sep 04 '25 16:09

Musaab


1 Answers

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)
like image 55
patrys Avatar answered Sep 07 '25 18:09

patrys