DEV Community

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

Posted on • Originally published at Medium

12 2

Django Tip: Use DecimalField for money

When working with money values in Django, the first thought is to use FloatField to represent currency in the model. However, FloatField uses the float 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 == .3
False
>>> .1 + .1 + .1
0.30000000000000004
Enter fullscreen mode Exit 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 with Decimal.

>>> from decimal import Decimal
>>> Decimal('.1') + Decimal('.1') + Decimal('.1') == Decimal('.3')
True
>>> Decimal('.1') + Decimal('.1') + Decimal('.1')
Decimal('0.3')
Enter fullscreen mode Exit 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 the DecimalField, it's always a good habit to precise the decimal_places attribute when defining the field.


class Product(models.Model):
    title = models.CharField(max_length=64)
    description = models.TextField()

    price = models.DecimalField(max_digits=6, decimal_places=2)
Enter fullscreen mode Exit fullscreen mode

You can learn more about DecimalField here.

Article posted using bloggu.io. Try it for free.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay