gurch101 - 1 year ago 126

Python Question

I'm trying to round money numbers in Decimal to the nearest 0.05. Right now, I'm doing this:

`def round_down(amount):`

amount *= 100

amount = (amount - amount % 5) / Decimal(100)

return Decimal(amount)

def round_up(amount):

amount = int(math.ceil(float(100 * amount) / 5)) * 5 / Decimal(100)

return Decimal(amount)

Is there any way I can do this more elegantly without dealing with floats using python Decimals (using quantize perhaps)?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

With floats, simply use `round(x * 2, 1) / 2`

. This doesn't give control over the rounding direction, though.

Using `Decimal.quantize`

you also get complete control over the type and direction of rounding (Python 3.5.1):

```
>>> from decimal import Decimal, ROUND_UP
>>> x = Decimal("3.426")
>>> (x * 2).quantize(Decimal('.1'), rounding=ROUND_UP) / 2
Decimal('3.45')
>>> x = Decimal("3.456")
>>> (x * 2).quantize(Decimal('.1'), rounding=ROUND_UP) / 2
Decimal('3.5')
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**