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)

      

+3


source to share


3 answers


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'

      

: -)

+3


source


you can use thisdirectly:



my_precision = lambda x, n: '{}'.format(round(x, n))

      

0


source


In 2019 with Python> = 3.6

Starting in Python 3.6 with PEP 498, you can use "f-strings" for formatting like this

>>> x = 123456
>>> n = 3
>>> f"{x:.{n}f}"
'123456.000'

      

Link here for more details:

0


source







All Articles