For Python f-string decimal places Include the type specifier in your format expression. When it comes to float
numbers, you can use format specifiers:
f'{value:{width}.{precision}}'
where:
value
is any expression that evaluates to a numberwidth
that specifies the number of characters used in total to display, but ifvalue
needs more space than the width specified then the additional space is used.precision
indicates the number of characters used after the decimal point
Consider:
>>> number1 = 10.1234
>>> f'{number1:.2f}'
'10.12'
Syntax:
"{" [field_name] ["!" conversion] [":" format_spec] "}"
Explanation:
# Let's break it down...
# [field_name] => number1
# ["!" conversion] => Not used
# [format_spec] => [.precision][type]
# => .[2][f] => .2f # where f means Fixed-point notation
Python f-string decimal places
Simple example code uses format specifiers with f strings.
# number of decimals
pi = 3.141592653589793238462643383279
print(f'The first 6 decimals of pi are {pi:.6f}.')
# convert to percentage
grade = 29/45
print(f'My grade rounded to 3 decimals is {grade:.3%}.')
# print constant length
from random import randint
for i in range(5):
print(f'My money is {randint(0, 150):>3}$')
# comma thousand separator
print(f'I am worth {10000000000:,}$')
Output:
Rounding floats with f-string
Using .2f
will round down to a total of 2 digits using scientific notation and will only work on float numbers instead of ints as well.
x = 3.14159265
print(f'pi = {x:.2f}')
Output: pi = 3.14
Here’s a more detailed example showing different numbers of decimal places:
number = 123.456789
# Format to 1 decimal place
formatted_1dp = f"{number:.1f}"
print(formatted_1dp) # Output: 123.5
# Format to 2 decimal places
formatted_2dp = f"{number:.2f}"
print(formatted_2dp) # Output: 123.46
# Format to 3 decimal places
formatted_3dp = f"{number:.3f}"
print(formatted_3dp) # Output: 123.457
# Format to 4 decimal places
formatted_4dp = f"{number:.4f}"
print(formatted_4dp) # Output: 123.4568
Do comment if you have any doubts or suggestions on this Python format string 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.