Django normalize() is showing 1E+1

76 Views Asked by At

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?

1

There are 1 best solutions below

0
Luciano Castillo On

Solution

You can fix it this way:

@property
def product_label(self):
    return f'The product price is {self.price.normalize():f}'

Just by adding :f after the method call, to format the Decimal object as fixed-point number.

Explanation

From the documentation:

normalize(context=None)

Normalize the number by stripping the rightmost trailing zeros and converting any result equal to Decimal('0') to Decimal('0e0'). Used for producing canonical values for attributes of an equivalence class. For example, Decimal('32.100') and Decimal('0.321000e+2') both normalize to the equivalent value Decimal('32.1').

So, it's not necessarily converting to a human-readable value.

In the FAQ section you can see some solutions provided like this one:

If an application does not care about tracking significance, it is easy to remove the exponent and trailing zeroes, losing significance, but keeping the value unchanged:

>>> from decimal import Decimal
>>> def remove_exponent(d):
...     return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
>>> remove_exponent(Decimal('5E+3'))
Decimal('5000')

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