Advertisement
Guest User

Untitled

a guest
Nov 23rd, 2012
348
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. g_carbs = DecimalField(max_digits=13, decimal_places = 8, null=True, blank=True)
  2.  
  3. from django.db.models.fields import DecimalField
  4.  
  5. class NonscientificDecimalField(DecimalField):
  6. def format_number(self, value):
  7. """
  8. Overrides DecimalField's usual format_number by making sure
  9. that the result is never in exponential notation for zero.
  10. """
  11. if value == 0:
  12. return "0.00000000"
  13. else:
  14. return super(DecimalField, self).format_number(value)
  15.  
  16. import decimal
  17. from django.db.models.fields import DecimalField
  18.  
  19. class NonscientificDecimalField(DecimalField):
  20. def format_number(self, value):
  21. """
  22. Overrides DecimalField's usual format_number to remove trailing zeroes.
  23. """
  24. if isinstance(value, decimal.Decimal):
  25. context = decimal.Context(prec=self.max_digits)
  26. value = value.normalize(context=context)
  27. return super(DecimalField, self).format_number(value)
  28.  
  29. class NonscientificDecimalField(DecimalField):
  30. """ Prevents values from being displayed with E notation, with trailing 0's
  31. after the decimal place truncated. (This causes precision to be lost in
  32. many cases, but is more user friendly and consistent for non-scientist
  33. users)
  34. """
  35. def value_from_object(self, obj):
  36. def remove_exponent(val):
  37. """Remove exponent and trailing zeros.
  38. >>> remove_exponent(Decimal('5E+3'))
  39. Decimal('5000')
  40. """
  41. context = decimal.Context(prec=self.max_digits)
  42. return val.quantize(decimal.Decimal(1), context=context) if val == val.to_integral() else val.normalize(context)
  43.  
  44. val = super(NonscientificDecimalField, self).value_from_object(obj)
  45. if isinstance(val, decimal.Decimal):
  46. return remove_exponent(val)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement