GafferMan2112 GafferMan2112 - 1 year ago 87
Python Question

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, say I want to display 2 digits after the decimal place. How do I do that?

a = 10.1234

Out[2]: '1e+01'

Out[3]: '10.12'

a = 100.1234

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?

Answer Source

Include the type specifier in your format expression:

>>> f'{a:.2f}'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download