Home > Net >  how to round a MoneyField in Django
how to round a MoneyField in Django

Time:02-25

Use django-money to reprent a product rate. The Model is defined as follows.

class ItemPrice(models.Model):
"""
Item price
"""
rate = MoneyField(_('Unit rate'), max_digits=10, decimal_places=2, default_currency='USD')

If I want to have the rounded rate in template, such as USD200 but not USD200.23, how to write the code?

CodePudding user response:

There are a couple of ways to do this. Firstly, you can modify integers and floats in your view logic, for example:

import math

rounded = math.floor(200.23)
print(rounded)
# result is 200

Also check out Django's floatformat template tags, which may suit your needs:

# for example in your view:

context = { 'value': 34.23234 }

# and in your template:

{{ value|floatformat:"0" }}

# will display 34

Documentation on floatformat tags here.

Note: I do not know what the particular features of the MoneyField are, since I don't think that's part of core Django. I'm assuming it stores floats.

CodePudding user response:

I wrote one.

@property
def standard_selling_rate_usd_rounded(self):
    amount = self.standard_selling_rate_usd.amount
    rounded = math.floor(int(amount))
    return Money(rounded, 'USD')
  • Related