Skip to content

Print up to 2 decimal places in Python | Example code

  • by

Use string format() function to up to 2 decimal places in Python. You need to Call str.format(number) with “{:.2f}” as str and a float as number to return a string representation of the number with two decimal places.

Here’s the general syntax for using format():

formatted_num = "{:.2f}".format(num)

The syntax for using the % operator:

formatted_num = "%.2f" % num

Example Print up to 2 decimal places in Python

Simple example code printing a float with two decimal places outputs.

num = 2.154327

res = "{:.2f}".format(num)

print(res)

Output:

Print up to 2 decimal places in Python

Another example

This will print up to digits after the decimal.

print("%.2f" % (70/105))

Output: 0.67

In this example, the % operator formats the number num with a precision of 2 decimal places using the format string "%.2f".

Do comment if you have any doubts or suggestions on this Python decimal topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading