13

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?

George Ogden
  • 596
  • 9
  • 15
  • Does this answer your question? [Limiting floats to two decimal points](https://stackoverflow.com/questions/455612/limiting-floats-to-two-decimal-points) – Kushan Gunasekera Feb 03 '21 at 00:00

2 Answers2

14

Fields in format strings can be nested:

>>> print(f"{math.pi:.{n}f}")
3.14159
Thomas
  • 174,939
  • 50
  • 355
  • 478
5

For pre-3.6 versions, you can use .format()

print('{:.{}}'.format(math.pi, n)))
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
BeanBagTheCat
  • 435
  • 4
  • 7