Print up to 2 decimal places in Python | Example code

Use sting 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.

Exmaple 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 decimal.

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

Output: 0.67

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

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.