Reputation: 533
Django Model:
class TwoDecimal(models.Model):
two_decimal = models.DecimalField(decimal_places=2, max_digits=10)
View:
def two_decimal(request):
test = TwoDecimal(
two_decimal = 30.00
)
test.save()
return render(
request,
"test-template.html",
{"test": test}
)
Template:
{{ test.two_decimal }} #==> Displays as 30.0 instead of 30.00 (Despite it being a two decimal field.)
This displays properly if it is a query from already saved data.
Why is django truncating this decimal place?
Upvotes: 1
Views: 382
Reputation: 477684
You should pass it a decimal, right now you pass it a float
. The fact that it is then saved in a DecimalField
does not make the attribute a Decimal
. If you would later retrieve it, then it indeed will be retrieved as a decimal.
from decimal import Decimal
def two_decimal(request):
test = TwoDecimal(
two_decimal = Decimal('30.00')
)
test.save()
return render(
request,
'test-template.html',
{'test': test}
)
Note that it is important to pass the value as a string to the Decimal
constructor. Otherwise it might introduce small rounding errors, and furthermore it does no longer contain information about the number of digits.
Upvotes: 1