drincruz
drincruz

Reputation: 168

How can I format a float to variable precision?

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

Answers (3)

RedNam
RedNam

Reputation: 415

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:

Upvotes: 24

fferri
fferri

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

fransua
fransua

Reputation: 1608

you can use thisdirectly :

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

Upvotes: -1

Related Questions