I'm trying to create a function in my model to display product info, and in my model I have the following:
class Product(models.Model):
price = models.DecimalField(max_digits=10, decimal_places=2)
@property
def product_label(self):
return f'The product price is {self.price.normalize()}'
Using normalize() is working fine if the price is something like 10.50 The output is as the following, which is what I exactly want:
The product price is 10.05
BUT when I have a price like 10.00, the output displayed shows 1E+1 instead of 10
The product price is 1E+1
Is there any idea how can I fix this issue?
Solution
You can fix it this way:
Just by adding
:fafter the method call, to format theDecimalobject as fixed-point number.Explanation
From the documentation:
So, it's not necessarily converting to a human-readable value.
In the FAQ section you can see some solutions provided like this one:
But in your case, it's enough to format the value.
Reference
Format specifiers
https://peps.python.org/pep-3101/#standard-format-specifiers
Decimal FAQ
https://docs.python.org/3/library/decimal.html#decimal-faq