Last active
September 23, 2016 06:01
-
-
Save 23maverick23/3943420 to your computer and use it in GitHub Desktop.
Django: Round price to 2 decimals
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
'float' object has no attribute 'quantize'