Python print format float | Example code

Use format() method to formatting a float number. Here are 2 ways to print format float in Python.

pi = 3.14159
print(" pi = %1.2f " % pi)         # old
print(" pi = {:.2f}".format( pi )) # new

Python print format float Example

Simple example code use str.format() to print the float with two decimal places.

The {} is the placeholder for substituted variables. If no format is specified, it will insert and format as a string.

pi = 3.1415926
precision = 2
print("{:.{}f}".format(pi, precision))

Output:

Python print format float

Number Formatting

The following table shows various ways to format numbers using Python’s

NumberFormatOutputDescription
3.1415926{:.2f}3.14Format float 2 decimal places
3.1415926{:+.2f}+3.14Format float 2 decimal places with sign
-1{:+.2f}-1.00Format float 2 decimal places with sign
2.71828{:.0f}3Format float with no decimal places
5{:0>2d}05Pad number with zeros (left padding, width 2)
5{:x<4d}5xxxPad number with x’s (right padding, width 4)
10{:x<4d}10xxPad number with x’s (right padding, width 4)
1000000{:,}1,000,000Number format with comma separator
0.25{:.2%}25.00%Format percentage
1000000000{:.2e}1.00e+09Exponent notation
13{:10d}13Right aligned (default, width 10)
13{:<10d}13Left aligned (width 10)
13{:^10d}13Center aligned (width 10)

Do comment if you have any doubts and suggestions on this Python float 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.