How to Format Float to 2 Decimal Places in Python?

❖ 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.

πŸ’» Awesome Tech Resources:
  • Looking for βš’οΈ tech jobs? Go to our job portal.
  • Looking for tech events? Go to tech events πŸ—“οΈ Calendar.️

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:

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:

Output:

Area = 78.54

3️⃣ % formatting

Solution:

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:

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:

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

Solution:

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:

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?

💡 Solution 1: Using a round()

Example:

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:

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! 😀

Related Posts

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.