
What does .2f mean in Python f-strings? Format a float with certain decimal places
Here is an example to format a float to two or three decimal points in Python.
a = 123.4567
s0 = '{:.0f}'.format(a)
s1 = '{:.1f}'.format(a)
s2 = '{:.2f}'.format(a)
s3 = '{:.3f}'.format(a)
s4 = '{:.4f}'.format(a)
s5 = '{:.5f}'.format(a)
print(a) # 123.4567
print(s0) # 123
print(s1) # 123.5
print(s2) # 123.46
print(s3) # 123.457
print(s4) # 123.4567
print(s5) # 123.45670
print(type(s3)) # <class 'str'>
The s0
doesn't have the decimal part because the format specification, which is after a colon in the curly braces like .2f
, set 0 digits. The s4
has 4 digits in the decimal parts because its format specification is .4f
. The .
means the decimal point and the next number means the digits of displayed representation.
Or you can format a float using the Python f-strings. The f-string is a string with f
prefix and can contain variables in the curly braces. The colon :
is a kind of border between a variable and format specification.
a = 123.4567
s0 = f'{a:.0f}'
s1 = f'{a:.1f}'
s2 = f'{a:.2f}'
s3 = f'{a:.3f}'
s4 = f'{a:.4f}'
s5 = f'{a:.5f}'
print(a) # 123.4567
print(s0) # 123
print(s1) # 123.5
print(s2) # 123.46
print(s3) # 123.457
print(s4) # 123.4567
print(s5) # 123.45670
Comments
Powered by Markdown