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
  • 398
  • 4
  • 11
  • 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
  • 162,537
  • 44
  • 333
  • 446
5

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

print('{:.{}}'.format(math.pi, n)))
Jean-François Fabre
  • 131,796
  • 23
  • 122
  • 195
BeanBagTheCat
  • 437
  • 3
  • 7