Python Django round to two decimal places

In this Python Django Tutorial, we’ll learn how to round to two decimal places in Django. And we’ll also see examples related to this. These are the following topics that we are going to discuss in this tutorial.

  • Python Django round to two decimal places
  • Python Django round to two decimal places basic commands
  • Python Django round to two decimal places view- round() function
  • Python Django round to two decimal places view- format() function
  • Python Django round to two decimal places view- % formatting
  • Python Django round to two decimal places view- ceil() function
  • Python Django round to two decimal places view- floor() function
  • Python Django round to two decimal places view- decimal module

Python Django round to two decimal places

In this section, we’ll learn basic knowledge of rounding off numbers up to two decimal places.

The floating-point numbers are divided into two parts integer part and the fractional part. And they are separated with the decimal point.

Examples: 12.36, 459.65, 885.3, etc are floating values.

Rule to round the decimal places:

If the number after the decimal place is given

  • Greater than and equal to 5: Then one is added to the final value.
  • Less than 5: Then the final number will be returned as it is up to the specified decimal places.

Methods to round the decimal places:

The following are the different methods available to round the decimal places.

  • round() function
  • format() function
  • ceil() function
  • floor() function
  • decimal module

Read Python Django where to save base template for all apps

Python Django round to two decimal places basic commands

In this section, we’ll learn basic commands to round off two decimal places.

CREATE PROJECT: First, we need to create a Django Project. For this, type the following command in the terminal.

django-admin startproject Employee
  • Here, Employee is the name of the Django Project.

CREATE APP: Then, we’ll create a Django App. For this, type the following command in the terminal.

python manage.py startapp Salary
  • Here, Salary is the name of the Django App.
READ:  What is Matplotlib inline in Python

INSTALL APP: Now, include the above-created app in the settings.py file.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'Salary',
]

CREATE TEMPLATES: Then create the folder with the name Templates. And, add HTML files within the folder.

python django round to two decimal places
Python Django round to two decimal places

ADD TEMPLATES: Now, add this folder Templates folder in the settings.py file.

DIRS : ['Templates']

PROJECT URLs: Add the following code in the urls.py file of Employee.

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('Salary.urls'))
]

APP URLs: Add the following code in the urls.py file of Salary.

from django.urls import path
from . import views
urlpatterns = [
path('', views.EmpSalary, name='EmpSalary'),
]

CREATE FORM: Now, add the following code to the forms.py file of the salary app to create the form.

from django import forms

class EmpSalaryForm(forms.Form):
    Name = forms.CharField()
    Designation = forms.CharField()
    Salary = forms.IntegerField()
    Tax = forms.FloatField()
  • Here, we create an EmpSalaryForm form class with two character fields, one integer field, and one float value field.

form.html: Add the following code to the form.html file to create a form.

<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <title>Index</title>  
</head>  
<body>  
<form method="POST" class="post-form" enctype="multipart/form-data">  
        {% csrf_token %}  
        {{ form.as_p }}  
        <button type="submit" class="save btn btn-default">Submit</button>  
</form>  
</body>  
</html> 
  • Here, we render the Django forms as a paragraph using the form.as_p tag.

salary.html: Add the following code to the salary.html file.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <p>
       <b>Tax amount round to two decimal : </b> {{RoundTax}}
    </p>
</body>
</html>

Read: Django CRUD example with PostgreSQL

Python Django round to two decimal places view- round() function

In this section, we’ll learn to round to two decimal places using round() methods.

Example: By using the round() function.

CREATE VIEW: Add the following code in the views.py file.

from django.shortcuts import render
from Salary.forms import EmpSalaryForm

def EmpSalary(request):  
    if request.method == "POST":  
        form = EmpSalaryForm(request.POST)  
        if form.is_valid():  
            Name = form.cleaned_data['Name']
            Designation = form.cleaned_data['Designation']
            Salary = form.cleaned_data['Salary']
            Tax = form.cleaned_data['Tax']
            RoundTax = round(Tax,2)
            return render(request, 'salary.html', {'RoundTax':RoundTax})
    else:  
        form = EmpSalaryForm()  
    return render(request,'form.html',{'form':form})
  • The round() function is a built-in python function.
  • It is used to return a floating-point value that has been rounded to the provided number of decimals.
  • Synatx:
    • round(number, digit)
  • If the digit argument is omitted, the closest integer to the given number is returned; otherwise, the number is rounded off to the given digit value.
python django round to two decimal places views
Python Django round to two decimal places views
django round to two decimal places views
Django round to two decimal places views-round()

Read: Python Django app upload files

READ:  How to encrypt and decrypt password in Django

Python Django round to two decimal places view- format() function

In this section, we’ll learn to round to two decimal places using format() methods.

Example: By using the format() function.

CREATE VIEW: Add the following code in the views.py file.

from django.shortcuts import render
from Salary.forms import EmpSalaryForm

def EmpSalary(request):  
    if request.method == "POST":  
        form = EmpSalaryForm(request.POST)  
        if form.is_valid():  
            Name = form.cleaned_data['Name']
            Designation = form.cleaned_data['Designation']
            Salary = form.cleaned_data['Salary']
            Tax = form.cleaned_data['Tax']
            RoundTax =("{:0.2f}".format(Tax))
            return render(request, 'salary.html', {'RoundTax':RoundTax})
    else:  
        form = EmpSalaryForm()  
    return render(request,'form.html',{'form':form})
  • We use the format() function to round numbers up by giving the string format as.2f.
  • The f in this format denotes a floating value, and the.2 specifies that the value must have two decimal places.
  • Syntax
"{:0.2f}".format(number)
python django round to two decimal places view-format() function
Python Django round to two decimal places view-format() function
django round to two decimal places view-format() function
Django round to two decimal places view-format() function

Read: Python filter not in Django

Python Django round to two decimal places view- % formatting

In this section, we’ll learn to round to two decimal places using % formatting.

Example: By using the % formatting.

CREATE VIEW: Add the following code in the views.py file.

from django.shortcuts import render
from Salary.forms import EmpSalaryForm

def EmpSalary(request):  
    if request.method == "POST":  
        form = EmpSalaryForm(request.POST)  
        if form.is_valid():  
            Name = form.cleaned_data['Name']
            Designation = form.cleaned_data['Designation']
            Salary = form.cleaned_data['Salary']
            Tax = form.cleaned_data['Tax']
            RoundTax =("%.2f" %Tax)
            return render(request, 'salary.html', {'RoundTax':RoundTax})
    else:  
        form = EmpSalaryForm()  
    return render(request,'form.html',{'form':form})
  • To get formatted output, we can alternatively use the % instead of the format() function.
  • It’s analogous to the format specifier in the print function.
  • Simply use the formatting with %.2f to round down to two decimal places.
  • Syntax:
"%.2f" % number
python django round to two decimal places view % formatting
Python Django round to two decimal places view % formatting
django round to two decimal places view % formatting
Django round to two decimal places view % formatting

Read: Python Django get enum choices

Python Django round to two decimal places view- ceil() function

In this section, we’ll learn to round to two decimal places using ceil() function.

Example: By using the ceil() method.

CREATE VIEW: Add the following code in the views.py file.

from math import ceil
from django.shortcuts import render
from Salary.forms import EmpSalaryForm

def EmpSalary(request):  
    if request.method == "POST":  
        form = EmpSalaryForm(request.POST)  
        if form.is_valid():  
            Name = form.cleaned_data['Name']
            Designation = form.cleaned_data['Designation']
            Salary = form.cleaned_data['Salary']
            Tax = form.cleaned_data['Tax']
            RoundTax = ceil(Tax*100)/100
            return render(request, 'salary.html', {'RoundTax':RoundTax})
    else:  
        form = EmpSalaryForm()  
    return render(request,'form.html',{'form':form})
  • The ceil() functions in the Python math module can round any value.
  • The ceil() function in this module returns the smallest integer that is greater than or equal to the value passed to it.
  • To use them for two decimal places, multiply the number by 100 first to shift the decimal point, then divide by 100 to compensate.
  • The final result will get rounded up with the ceil() function.
  • Syntax:
from math import ceil
ceil(number*100)/100
python django round to two decimal places view ceil function
Python Django round to two decimal places view ceil function
django round to two decimal places view ceil function
Django round to two decimal places view ceil function

Read: Outputting Python to html Django

READ:  Python Scipy Optimize Root

Python Django round to two decimal places view- floor() function

In this section, we’ll learn to round to two decimal places using the floor function.

Example: By using the floor() method.

CREATE VIEW: Add the following code in the views.py file.

from math import floor
from django.shortcuts import render
from Salary.forms import EmpSalaryForm

def EmpSalary(request):  
    if request.method == "POST":  
        form = EmpSalaryForm(request.POST)  
        if form.is_valid():  
            Name = form.cleaned_data['Name']
            Designation = form.cleaned_data['Designation']
            Salary = form.cleaned_data['Salary']
            Tax = form.cleaned_data['Tax']
            RoundTax = floor(Tax*100)/100
            return render(request, 'salary.html', {'RoundTax':RoundTax})
    else:  
        form = EmpSalaryForm()  
    return render(request,'form.html',{'form':form})
  • The floor() function returns the largest number that is less than or equal to the value given to it.
  • The final result will be rounded down if we use the floor() function.
  • Syntax:
from math import floor
floor(number*100)/100
python django round to two decimal places view floor function
Python Django round to two decimal places view floor function
django round to two decimal places view floor function
Django round to two decimal places view floor function

Read: Python Django random number

Python Django round to two decimal places view- decimal module

In this section, we’ll learn to round to two decimal places using the decimal module.

Example: By using the decimal() method.

CREATE VIEW: Add the following code in the views.py file.

from decimal import ROUND_HALF_DOWN, Decimal
from django.shortcuts import render
from Salary.forms import EmpSalaryForm

def EmpSalary(request):  
    if request.method == "POST":  
        form = EmpSalaryForm(request.POST)  
        if form.is_valid():  
            Name = form.cleaned_data['Name']
            Designation = form.cleaned_data['Designation']
            Salary = form.cleaned_data['Salary']
            Tax = form.cleaned_data['Tax']
            RoundTax = Decimal(Tax.quantize(Decimal('.01'), rounding = ROUND_HALF_DOWN))
            return render(request, 'salary.html', {'RoundTax':RoundTax})
    else:  
        form = EmpSalaryForm()  
    return render(request,'form.html',{'form':form})
  • Python has a decimal module with several functions for dealing with decimal values.
  • It can be used to round float values to two decimal places.
  • The “rounding half down” method achieved the needed precision by rounding to the nearest number.

Note:

Set the field to decimal if you want to execute precision calculations; otherwise, an error will be generated.

Example:

Tax=form.DecimalField()
python django round to two decimal places view decimal module
Python Django round to two decimal places view decimal module
django round to two decimal places view decimal module
Django round to two decimal places view decimal module

Also, take a look at some more Python Django tutorials.

In this tutorial, we have discussed “Python Django round to two decimal places” and we have also discussed the following topics in this tutorial.

  • Python Django round to two decimal places
  • Python Django round to two decimal places basic commands
  • Python Django round to two decimal places view- round() function
  • Python Django round to two decimal places view- format() function
  • Python Django round to two decimal places view- % formatting
  • Python Django round to two decimal places view- ceil() function
  • Python Django round to two decimal places view- floor() function
  • Python Django round to two decimal places view- decimal module