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.

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

  • 25 October

    Increment operator in python

    Table of ContentsPython’s distinct way of using the increment operatorWays to increment a variable in PythonUsing the augmented assignment operatorUsing the step parameter in the range() functionThe role of immutability in Python The increment process is among the basic and the essentials of any programming language. We use it in problem-solving and when there is […]

  • How to comment out multiple lines in python
    16 October

    How to comment out multiple lines in python

    Table of ContentsMultiple Line Comments in PythonUsing the # characterUsing triple quotesUsing IDEs and Text Editors In this article, we will see about how to comment out multiple lines in python. The concept of comments is present in most programming languages. We use comments for documentation purposes. The compiler ignores them, but the user can […]

  • Get variable name as String in Python
    01 October

    How to get variable name as String in Python

    Table of ContentsWhat are variable names in Python?How to get a variable name as a string in Python?In Python 2.xIn Python 3.x In Python, there are several ways to convert a string to a variable name, but the reverse process is not exactly utilized so often in the programming world. This article focuses on how […]

  • Python print percent sign
    30 September

    Print percentage sign in python

    Table of ContentsIntroductionPrint the Percentage Sign in PythonUsing the %% characterUsing the format() functionUsing the f-string Introduction In this tutorial, we will see how to print percentage sign in python. The modulus operator (%) or the percentage sign has multiple usages in Python. We use this operator to calculate the remainder for the division between […]

  • Print blank line in Python
    23 September

    Print blank line in Python

    Table of ContentsWhat is a blank line in Python?Ways to print blank line in PythonUsing an empty print() functionUsing the print() function with newline characterUsing the print() function with an empty stringUsing the print() function with the sep parameterWays to print multiple blank lines in PythonUsing the print() function with multiple newline charactersUsing the print() […]

  • 17 September

    Write list to CSV in Python

    Table of ContentsUsing the write() function to write a list to a CSV fileUsing the csv module to write a list to a CSV fileUsing the numpy module to write a list to a CSV fileUsing the numpy.savetxt() function to write a list to a CSV fileUsing the numpy.tofile() function to write a list to […]

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.