Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Django Tip: Use DecimalField for money
Mangabo Kolawole
Mangabo KolawoleSubscriber

Posted on • Originally published atMedium

     

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
Enter fullscreen modeExit fullscreen mode

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')
Enter fullscreen modeExit fullscreen mode

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)
Enter fullscreen modeExit fullscreen mode

You can learn more aboutDecimalFieldhere.

Article posted usingbloggu.io. Try it for free.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Software Engineer | Technical Writer | Book Author
  • Location
    Remote
  • Education
    Studied CS
  • Work
    Software Engineer
  • Joined

More fromMangabo Kolawole

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp