Musaab - 8 months ago 38

Python Question

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

`decimal`

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

Answer

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)
```

Source (Stackoverflow)