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)
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With