Django Tip: Use DecimalField for money
When working with money values in Django, the first thought is to useFloatField
to represent currency in the model. However,FloatField
uses thefloat
type internally which comes with some precision issues.
The problem
Take a look at this piece of code. It's just a simple operation with float numbers in Python.
>>>.1+.1+.1==.3False>>>.1+.1+.10.30000000000000004
Normally, you think that the addition will make sense but because of some issues with the float approximation, the equation is not equal to 3.
You can fix these issues using rounding but if you are dealing with money values and precision matters, it might be time to use decimals.
The solution
Basically, use decimals instead of floats when precision matters. Let's rewrite the previous example but withDecimal
.
>>>fromdecimalimportDecimal>>>Decimal('.1')+Decimal('.1')+Decimal('.1')==Decimal('.3')True>>>Decimal('.1')+Decimal('.1')+Decimal('.1')Decimal('0.3')
Notice that here we are initializing the decimals values with string values. You can use floats but as we said earlier, floats have their approximation issues.
Then when working with Decimal in Django with theDecimalField
, it's always a good habit to precise the decimal_places attribute when defining the field.
classProduct(models.Model):title=models.CharField(max_length=64)description=models.TextField()price=models.DecimalField(max_digits=6,decimal_places=2)
You can learn more aboutDecimalField
here.
Article posted usingbloggu.io. Try it for free.
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse