Fixed digits after decimal with f-strings

GafferMan2112 picture GafferMan2112 · Jul 25, 2017 · Viewed 146.1k times · Source

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

Answer

Robᵩ picture Robᵩ · Jul 25, 2017

Include the type specifier in your format expression:

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