Fixed digits after decimal with f-lines

Is there an easy way with Python f-lines (PEP 498) to fix the number of digits after a decimal point? (In particular, f-strings, not other string formatting options such as .format or%)

For example, let's say I want to display 2 digits after a decimal point. How to do it?

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” changed the value “number of places after the decimal point”, as is the case when using the formatting%, but only by numbers. How can I always get 2 digits after the decimal sum, no matter how many numbers I have?

+7
python f-string
source share
1 answer

Include a type specifier in a format expression:

 >>> f'{a:.2f}' '10.12' 
+16
source share

All Articles