Fixed digits after decimal with f-strings

Is there an easy way with Python f-strings (PEP 498) 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?

    a = 10.1234

    f'{a:.2}'
    Out[2]: '1e+01'

    f'{a:.4}'
    Out[3]: '10.12'

    a = 100.1234

    f'{a:.4}'
    Out[5]: '100.1'

As you can see "precision" has changed meaning from "number of places after the decimal point" as is the case when using % formatting, to just total digits. How can I always get 2 digits after the decimal, no matter how big a number I have?

Include the type specifier in your format expression:

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

From: stackoverflow.com/q/45310254

Back to homepage or read more recommendations: