Round Numbers to Two Decimal Places in Python Django

Handling decimal places was a common challenge, especially when dealing with financial or scientific data. Rounding numbers accurately to two decimal places is necessary in many real-world applications, such as displaying prices, calculating taxes, or formatting user inputs.

In this article, I will share practical methods I’ve used over the years to round numbers to two decimal places in Django projects.

Let’s get in!

Methods to Round to Two Decimal Places in Django

In many US-based applications, especially those involving currency, it’s standard practice to round numbers to two decimal places. This is because dollars and cents are expressed with two decimals. For example, showing a price as $12.345 is incorrect; it should be $12.35.

Improper rounding can cause issues in billing systems, reporting, and user experience. Django developers often need to handle this both on the backend (in views, models, or forms) and on the frontend (templates).

Check out Integrity Error in Django

Method 1: Use Python’s Built-In round() Function

The simplest way to round a number to two decimal places in Django is by using Python’s built-in round() function. This function takes two arguments: the number to round and the number of decimal places.

Here’s a quick example:

# views.py
def price_view(request):
    price = 12.34567
    rounded_price = round(price, 2)  # rounds to 12.35
    return HttpResponse(f"The rounded price is ${rounded_price}")

You can refer to the screenshot below to see the output.

django template round

This method is simple and works well when you just need to round floating-point numbers for display or calculations.

However, keep in mind that floating-point arithmetic can sometimes cause precision issues because of how numbers are stored in binary.

Read Django Programming Error: Column does not exist

Method 2: Use Python’s Decimal Module for Precise Rounding

For financial applications, I always prefer using the Decimal module from Python’s standard library. It provides more accurate decimal arithmetic and rounding control.

Here’s how you can use Decimal with Django:

from decimal import Decimal, ROUND_HALF_UP

def price_view(request):
    price = Decimal('12.34567')
    rounded_price = price.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)  # rounds to 12.35
    return HttpResponse(f"The rounded price is ${rounded_price}")

You can refer to the screenshot below to see the output.

django round

In this example, quantize() rounds the decimal to exactly two decimal places using the ROUND_HALF_UP strategy, which is the typical rounding method used in financial contexts.

Using Decimal ensures that rounding behaves exactly as expected, avoiding surprises caused by floating-point approximations.

Check out Create a Music Player Application using Django

Method 3: Format Numbers in Django Templates

Sometimes, you want to round numbers directly in your Django templates, especially when displaying values passed from views.

Django’s built-in floatformat template filter is handy for this:

<!-- template.html -->
<p>Price: ${{ price|floatformat:2 }}</p>

You can refer to the screenshot below to see the output.

django template round decimal

If price is 12.34567, this will display as $12.35.

Note that floatformat rounds the number but returns a string, so it’s best used for display purposes only.

Read Create a Dictionary Application in Django

Method 4: Custom Template Filter for Decimal Rounding

If you need more control in templates, you can create a custom template filter that uses Decimal rounding.

Here’s how:

  1. Create a templatetags directory inside your app with an __init__.py file.
  2. Add a file custom_filters.py:
from django import template
from decimal import Decimal, ROUND_HALF_UP

register = template.Library()

@register.filter
def round_two_decimals(value):
    try:
        d = Decimal(value)
        return d.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
    except:
        return value
  1. Load and use it in your template:
{% load custom_filters %}

<p>Price: ${{ price|round_two_decimals }}</p>

This approach combines the accuracy of Decimal with the flexibility of Django templates.

Check out Django User Registration with Email Confirmation

Method 5: Round in Django Models with DecimalField

When storing decimal numbers in Django models, you typically use DecimalField which stores fixed-point decimal numbers.

You can ensure values are rounded before saving by overriding the model’s save() method:

from django.db import models
from decimal import Decimal, ROUND_HALF_UP

class Product(models.Model):
    name = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=10, decimal_places=4)

    def save(self, *args, **kwargs):
        if self.price:
            self.price = self.price.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
        super().save(*args, **kwargs)

This guarantees that the price is always rounded to two decimal places before saving to the database.

Read Python Django Import Functions

My Recommended Approach

From my experience, using the Decimal module is the best practice for rounding in Django projects, especially when accuracy matters.

For display purposes, combining backend rounding with Django’s floatformat or a custom template filter provides clean and user-friendly output.

Avoid relying solely on floating-point round() for financial data due to potential precision errors.

Rounding numbers to two decimal places in Django is simple once you know the right tools. Whether you’re dealing with user input, displaying prices, or saving data, these methods will help you maintain precision and professionalism in your applications.

If you’re building an e-commerce site, financial dashboard, or any app where decimals matter, applying these techniques will save you headaches down the road.

Feel free to experiment with these methods and choose the one that fits your project’s needs best.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.