I have few places in database when I'm using DecimalField. Unfortunalety I have to handle both double and float data as input - and there is my problem.
I want to do brutal cut off the value (after second decimal place), not a math round. I store calculated value which goal is to be exceeded hardly (if I have value 49.9832100000032131 it is still less than 50, so I won't round it up). But as i said - I want to save it as 48.98 in database (with 2 decimal places) - saving memory and enough representation.
My first solution is using custom django field, something like this:
class DecimalFixedField(models.DecimalField):
def __init__(self, *args, **kwargs):
kwargs['value'] = "{0:.2f}".format( kwargs['value'] )
# or ? self.value = "{0:.2f}".format( kwargs['value'] )
super(DecimalFixedField, self).__init__(*args, **kwargs)
Of course I should hardcode decimal_places = 2 in kwargs or use it in code not value 2, but... what about rest? Do you have hint, better idea?
What is important - I don't wanna write "{0:.2f}".format(...) in many places in code! I wanted to do it in OOP methodology, because I'm using DecimalField in many models... and making this pre-processing looks as nice solution. Any thoughts how it shoud be implemented properly?