How can I format a float to variable precision?
In 2019 with Python >= 3.6
From Python 3.6 with PEP 498, you can use "f-strings" to format like this
>>> x = 123456
>>> n = 3
>>> f"{x:.{n}f}"
'123456.000'
Reference here for more detail:
- PEP 498
- realpython.com Guide
Your solution is fine.
However, as a personal matter of style, I tend to use either only %
, or only str.format()
.
So in this case I would define your formatting function as:
def my_precision(x, n):
return '{:.{}f}'.format(x, n)
(thanks to @MarkDickinson for suggesting an shorter alternative to '{{:.{:d}f}}'.format(n).format(x)
)
Incidentally, you can simply do:
my_precision = '{:.{}f}'.format
and it works:
>>> my_precision(3.14159, 2)
'3.14'
:-)