Open In App

How to get two decimal places in Python

Last Updated : 16 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

In Python programming, while working on financial calculations, a need to round a value to two decimal places may arise. Handling this precision of float-point values is quite easy as there are many ways to do that.

Let's explore a simple example to get two decimal places in Python.

Python
pi = 3.14159265359
print(round(pi, 2))

Output
3.14

Explanation: The Python built-in round() function is used to round off a number to a specified number of decimal places. It takes two parameters, the number to be rounded off, and an optional parameter, the number up to which the given number is to be rounded.

Now let us see different ways to get two decimal places in Python one by one.

Using String Formatting

The f-string in Python is used to format a string. It can also be used to get 2 decimal places of a float value. It directly embeds the expression inside the curly braces.

Python
pi = 3.14159265359
print(f"{pi:.2f}")

Output
3.14

Using format() Function

Python format() function is an inbuilt function used to format strings. Unlike f-string, it explicitly takes the expression as arguments.

Python
pi = 3.14159265359
print("{:.2f}".format(pi))

Output
3.14

Using % Operator

The % operator can also be used to get two decimal places in Python. It is a more traditional approach which makes the use of string formatting technique.

Python
pi = 3.14159265359
print("%.2f" % pi)

Output
3.14

Using math Module

Python math module provides various function that can be used to perform various mathematical operations on the numbers. Once such function is the floor() function which is used to round down the float value to the nearest integer. The to get exact two decimal places, the number is to be first multiplied by 100 before applying the floor() function. And the final step includes dividing the number by 100.

Python
import math

pi = 3.14159265359
print(math.floor(pi * 100) / 100)

Output
3.14

Using decimal Module

The decimal module provides various functions that can be used to get two decimal places of a float value. The Decimal() function is used to convert the float-point value to a decimal object. Then the quantize() function is used to set the decimal to a specific format. This function takes the format of "0.00" which means two decimal points.

Python
from decimal import Decimal

pi = 3.14159265359

# converting number to decimal value
num = Decimal(pi)

# rounding off the decimal to two decimal place
result = num.quantize(Decimal("0.00"))
print(result)

Output
3.14

Next Article
Article Tags :
Practice Tags :

Similar Reads