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

  • Convert String to Boolean in Python
    20 June

    Convert String to Boolean in Python

    Table of ContentsUsing the bool() method to convert string to Boolean in Python.Using the distutils.util.strtobool() method to convert a string to Boolean in Python.Using list comprehension to convert a string to Boolean in Python.Using the map() function along with Lambda function to convert a string to Boolean in Python.Using the JSON parser to convert a […]

  • Convert float to int in Python
    19 June

    Convert float to int in Python

    Table of ContentsUsing the int() function to convert float to int in PythonUsing the math module functions to convert float to int in PythonUsing ceil()Using trunc()Using floor Python provides several in-built functions and modules for datatype conversions. Floating-point numbers can be easily converted to integers using some of these in-built functions. This tutorial will discuss […]

  • Detect keypress in Python
    12 June

    Detect keypress in Python

    Table of ContentsUsing the keyboard module to detect keypress in PythonUsing the pynput module to detect keypress in PythonUsing the msvcrt module to detect keypress in Python Python allows us to work with user input in its programs. We can also work with hardware devices in Python. In this article, we will discuss how to […]

  • Copy a dictionary in Python
    12 June

    7 ways to copy a dictionary in python

    Table of ContentsUsing the copy() function to copy a dictionary in PythonUsing the deepcopy() function to copy a dictionary in PythonUsing the dict() function to copy a dictionary in PythonUsing the unpack operator ** to copy a dictionary in PythonUsing the update() function to copy a dictionary in PythonUsing the dictionary comprehension method to copy […]

  • Escape quotes in Python
    11 June

    Escape quotes in Python

    Table of ContentsUsing \ to escape quotes in PythonUsing \ with replace() to escape quotes in PythonUsing json.dumps to escape quotes in PythonUsing triple single or double quotes to escape quotes in pythonUse r to include \ and quotes in String 💡 Outline You can use \ to escape quotes in Python. If you want […]

  • Sleep for milliseconds in python
    31 May

    How to sleep for milliseconds(ms) in Python

    Table of ContentsUse time.sleep() function to make the program sleep for millisecondsUse threading.Timer() function to make the program sleep for milliseconds 💡 Outline You can use time.sleep() method to sleep for milliseconds in Python. If you want to delay python program by 500 ms, then you need to pass 0.5 as parameter to sleep method. […]

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.