Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round python decimal to nearest 0.05

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

like image 557
gurch101 Avatar asked Dec 10 '22 16:12

gurch101


1 Answers

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')
like image 86
taleinat Avatar answered Dec 24 '22 13:12

taleinat