Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I format a float to variable precision?

Tags:

python

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)
like image 511
drincruz Avatar asked Jun 17 '15 16:06

drincruz


1 Answers

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
like image 79
RedNam Avatar answered Nov 02 '22 13:11

RedNam