Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- g_carbs = DecimalField(max_digits=13, decimal_places = 8, null=True, blank=True)
- from django.db.models.fields import DecimalField
- class NonscientificDecimalField(DecimalField):
- def format_number(self, value):
- """
- Overrides DecimalField's usual format_number by making sure
- that the result is never in exponential notation for zero.
- """
- if value == 0:
- return "0.00000000"
- else:
- return super(DecimalField, self).format_number(value)
- import decimal
- from django.db.models.fields import DecimalField
- class NonscientificDecimalField(DecimalField):
- def format_number(self, value):
- """
- Overrides DecimalField's usual format_number to remove trailing zeroes.
- """
- if isinstance(value, decimal.Decimal):
- context = decimal.Context(prec=self.max_digits)
- value = value.normalize(context=context)
- return super(DecimalField, self).format_number(value)
- class NonscientificDecimalField(DecimalField):
- """ Prevents values from being displayed with E notation, with trailing 0's
- after the decimal place truncated. (This causes precision to be lost in
- many cases, but is more user friendly and consistent for non-scientist
- users)
- """
- def value_from_object(self, obj):
- def remove_exponent(val):
- """Remove exponent and trailing zeros.
- >>> remove_exponent(Decimal('5E+3'))
- Decimal('5000')
- """
- context = decimal.Context(prec=self.max_digits)
- return val.quantize(decimal.Decimal(1), context=context) if val == val.to_integral() else val.normalize(context)
- val = super(NonscientificDecimalField, self).value_from_object(obj)
- if isinstance(val, decimal.Decimal):
- return remove_exponent(val)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement