How to Format Float to 2 Decimal Places in Python?

[toc]

❖ Problem Formulation

In this article, you will learn how to format a floating-point value and generate a float number with two decimal places.

Example: In the following code, we are calculating the area of a circle.

import math

radius = 5
area = math.pi*radius*radius
print("Area = ", area)

Output:

Area = 78.53981633974483

Since the value of math.pi is 3.141592653589793, hence the output also yields a value up to fifteen decimal places. However, you want to generate an output up to two decimal places, i.e., Area = 78.54

Hence, without further delay, let us dive into the solutions to our problem.

💡 Method 1: Using String Formatting

Python majorly has 3 ways of formatting a string. These are –

  • str.format()
  • f-string (String Literal)
  • % formatting

Let’s see how we can use these methods to format a floating-point value to two decimal places.

1️⃣ str.format()

  • format() is a method in Python that formats specific values and inserts them in the placeholder {} of the string.
  • It returns the formatted string.

Syntax:

string.format(value1, value2...)

You can use str.format(number) along with .2f inside the placeholder, i.e., {:.2f} . This returns a string representation of the number up to two decimal places, as shown below.

Solution:

import math

radius = 5
area = math.pi*radius*radius
print("Area = {:.2f}".format(area))

Output:

Area = 78.54

📌Another way of using the format operator to print up to two decimal places is as follows:

print("Area = ", format(area, '.2f'))

⚠️Caution: str.format() was introduced in Python 2.6. Hence, you cannot use it in versions prior to Python 2.6.

2️⃣ f-string

An f-string is a string literal in Python that has the prefix ‘f‘ containing expressions inside curly braces. These expressions can be replaced with their values.

Thus, you can use f'{value: .2f}' to return a string representation of the number up to two decimal places.

Solution:

import math

radius = 5
area = math.pi*radius*radius
print(f"Area = {area:.2f}")

Output:

Area = 78.54

3️⃣ % formatting

Solution:

import math

radius = 5
area = math.pi * radius * radius
print("Area = %.2f" % area)

Output:

Area = 78.54

💡 Method 2: Using round() Function

round() is an inbuilt method in Python that rounds off a decimal number with a specified number of digits.

Syntax:

round(number, digits)

Thus, you can use round(value,2) to return a floating-point number up to two decimal places.

Solution:

import math

radius = 5
area = math.pi * radius * radius
print("Area = ", round(area, 2))

Output:

Area = 78.54

💡 Method 3: Using the Decimal Object

Another workaround to our problem is to use the Decimal object, and the quantize function to return a float value with two decimal places.

quantize method returns a value by rounding the first operand and having the exponent of the second operand. For example:

from decimal import Decimal
print(Decimal('3.141592653589793').quantize(Decimal('1.000'))))

# 3.142

Now let’s visualize how we can use this to solve our problem.

Solution:

import math
from decimal import Decimal

radius = 5
area = Decimal(math.pi * radius * radius)
print("Area = ", area.quantize(Decimal('0.01')))

Output:

Area = 78.54

💡 Method 4: Using a Lambda Function

This is a little hack to solve our problem using a lambda function. You can make the lambda function return the formatted value up to two decimal places, as shown in the solution below.

Solution:

import math

radius = 5
area = math.pi * radius * radius
foo = lambda x : x*(10**2)//1/(10**2)
print("Area = ", foo(area))

Output:

Area = 78.53

Note: This is not the most efficient way to solve our problem if precision is your priority. Even though it formats the decimal value to two places, it does not round off the floating-point value effectively, i.e., 78.539  → 78.54; however, this computation doesn’t occur while using the above method.

🏆 BONUS – How to round each item in a list of floats to 2 decimal places in Python?

Before wrapping up this discussion, let us have a quick look at a couple of methods that allow you to round each float value within a list to 2 decimal places.

Problem: Given the following list, how will you round off each value to 2 decimal places?

values = [22.459, 5.963, 2.335,-1.569, -0.019, -22.3]

💡 Solution 1: Using a round()

Example:

values = [22.459, 5.963, 2.335,-1.569, -0.019, -22.3]
new_values = [round(value, 2) for value in values]
print("Original List:", values)
print("Rounded List:", new_values)

Output:

Original List: [22.459, 5.963, 2.335, -1.569, -0.019, -22.3]
Rounded List: [22.46, 5.96, 2.33, -1.57, -0.02, -22.3]

💡 Solution 2: Using String formatting

Example:

values = [22.459, 5.963, 2.335,-1.569, -0.019, -22.3]
new_values = ['%.2f' % elem for elem in values]
print("Original List:", values)
print("Rounded List:", new_values)

Output:

Original List: [22.459, 5.963, 2.335, -1.569, -0.019, -22.3]
Rounded List: [‘22.46’, ‘5.96’, ‘2.33’, ‘-1.57’, ‘-0.02’, ‘-22.30’]

❖ Conclusion

Thus, in this article, you learned:

  • How to use string formatting methods to format a float value to two decimal places?
  • Using the round function.
  • Using the Decimal object and the quantize method.
  • How to round each item in a list of floats to 2 decimal places?

With that, we come to the end of this comprehensive guide. I hope it helped you. Please stay tuned and subscribe for more interesting contents in the future. Happy learning! 😀

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.