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

Was this post helpful?


import_contacts

You may also like:

Related Posts

  • 29 June

    Get Day Name from Date in Python

    Table of ContentsUse the Calendar Module to Get the Name of the Day in PythonUse the strftime() Method to Get the Name of the Day in PythonUse Pandas Timestamp Method to Get the Name of the Day in PythonUse the weekday() Method to Get the Name of the Day in PythonUse the isoweekday() Method to […]

  • 27 June

    Fill Array with Random Numbers in Python

    Table of ContentsFill array with random numbers in PythonWays to fill array with random numbers in PythonUsing the numpy.random.randint() function to fill array with random numbers in PythonUsing the numpy.random.Generator.integers() function to fill array with random numbers in PythonUsing the random.randint() function to fill array with random numbers in PythonConclusionWas this post helpful? Fill array […]

  • 25 June

    Convert Roman Number to Integer in Python

    Table of ContentsHow to Convert Roman Number to Integer in PythonHow to convert roman number to integer in python?Using the if...else statement to convert roman number to integer in Python.Using classes and a dictionary to convert roman number to integer in Python.Using the roman module to convert roman number to integer in Python.ConclusionWas this post […]

  • 11 June

    Remove Single Quotes from String in Python

    Table of ContentsRemove single quotes from string in Python.How to remove single quotes from string in Python?Using the replace() function to remove single quotes from string in Python.Using a for loop to remove single quotes from string in Python.Using the join() function to remove single quotes from string in Python.Using the re module functions to […]

  • 11 June

    Escape Backslash Character in Python

    Table of ContentsEscape backslash character in python.How to use escape backslash character in python?Using the escape backslash character in python to represent whitespace characters.Using the escape backslash character in python to turn special characters into ordinary characters.Using the escape backslash character in f-strings in Python.Using the escape backslash character in raw strings in Python.Was this […]

  • 11 June

    Break out of function in Python

    Table of ContentsBreak out of function in PythonHow to break out of function in Python?Using the return statement to break out of function in PythonUsing the try and except block to break out of function in PythonUsing the sys.exit() function to break out of function in PythonConclusionWas this post helpful? In this post, we will […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.