How can a float be formatted with variable precision?
I would like to have a function that formats a float with variable length precision. For example, if I go to n = 2, I would expect an accuracy of 1.67; if i pass in n=5
i would expect 1.66667
.
I currently have the following, but I feel there will be an easier way to do this. There is?
def my_precision(x, n):
fmt = '{:.%df}' % n
return fmt.format(x)
source to share
Your solution is fine.
However, as a personal 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 a shorter alternative '{{:.{:d}f}}'.format(n).format(x)
)
By the way, you can simply do:
my_precision = '{:.{}f}'.format
and it works:
>>> my_precision(3.14159, 2)
'3.14'
: -)
source to share