Skip to content

Python f-string decimal places

  • by

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 number
  • width that specifies the number of characters used in total to display, but if value 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 use 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:

Python f-string decimal places

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

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.

Leave a Reply

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