Skip to content

Instantly share code, notes, and snippets.

@23maverick23
Last active September 23, 2016 06:01
Show Gist options
  • Save 23maverick23/3943420 to your computer and use it in GitHub Desktop.
Save 23maverick23/3943420 to your computer and use it in GitHub Desktop.
Django: Round price to 2 decimals
@property
def update_price(self):
"""
Return a rounded price using the quantity and rate.
This utilizes the Decimal object to get around the strange
rounding behavior in Python with Base 10. The logic converts
both operands to Decimal objects, multiplies them, then
performs a ROUND_UP method using 2 decimal places.
"""
from decimal import *
q = Decimal(self.quantity)
r = Decimal(self.rate)
if q > 0.00 and r > 0.00:
p = q * r
return p.quantize(Decimal('.01'), rounding=ROUND_UP)
else:
return 0.00
@abhibalani
Copy link

'float' object has no attribute 'quantize'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment