Reputation: 168
I would like to have a function that formats a float to a variable length of precision. For example, if I pass in n=2, I would expect a precision of 1.67; if I pass in n=5
, I would expect 1.66667
.
I currently have the following, but I feel like there would be an easier way to do so. Is there?
def my_precision(x, n):
fmt = '{:.%df}' % n
return fmt.format(x)
Upvotes: 15
Views: 6186
Reputation: 415
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:
Upvotes: 24
Reputation: 18950
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'
:-)
Upvotes: 12
Reputation: 1608
you can use thisdirectly :
my_precision = lambda x, n: '{}'.format(round(x, n))
Upvotes: -1