I have a variable n
and I want to print n decimal places.
import math
n = 5
print(f"{math.pi:.nf}")
ValueError: Format specifier missing precision
This doesn't work, but how might it be done?
Python has a built-in round() function that takes two numeric arguments, n and ndigits , and returns the number n rounded to ndigits . The ndigits argument defaults to zero, so leaving it out results in a number rounded to an integer.
Fields in format strings can be nested:
>>> print(f"{math.pi:.{n}f}")
3.14159
For pre-3.6 versions, you can use .format()
print('{:.{}}'.format(math.pi, n)))
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