pythonpython-3.xf-string

Fixed digits after decimal with f-strings


Is there an easy way with Python f-strings to fix the number of digits after the decimal point? (Specifically f-strings, not other string formatting options like .format or %)

For example, let's say I want to display 2 digits after the decimal place.

How do I do that? Let's say that

a = 10.1234

Solution

  • Include the type specifier in your format expression:

    >>> a = 10.1234
    >>> f'{a:.2f}'
    '10.12'