Skip to content

Python float format

  • by

There are various methods for formatting float numbers in Python. The best way is to use the format() function to To format float values in Python.

Python float format example

Simple example code format float number in python.

x = 211911461911461819112146
y = 2 ** 70
z = x / y

print(z)
print("{:.2f}".format(z))

print(float("{:.2f}".format(z))) # float

Output:

Python float format

Format float value using the round() Method

x = 211911461911461819112146
y = 2**70
z = x / y

print(round(z, 2)) # 179.5

Using f-strings

x = 211911461911461819112146
y = 2**70
z = x / y

print(f'{z:.2f}') #179.50

Use the %f Formatter

floatNumber = 1.9876

print("%f" % floatNumber) # 1.987600

Python float format Table

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
4{:0>2d}04Pad number with zeros (left padding, width 2)
4{:x<4d}4xxxPad 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.35{:.2%}35.00%Format percentage
1000000000{:.2e}1.00e+09Exponent notation
11{:11d}        11Right-aligned (default, width 10)
11{:<11d}11Left-aligned (width 10)
11{:^11d}    11Center aligned (width 10)

Comment if you have any doubts or suggestions on this Python float 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

Your email address will not be published. Required fields are marked *