George Ogden
George Ogden

Reputation: 835

How to format to n decimal places in Python

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?

Upvotes: 13

Views: 856

Answers (2)

BeanBagTheCat
BeanBagTheCat

Reputation: 445

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

print('{:.{}}'.format(math.pi, n)))

Upvotes: 5

Thomas
Thomas

Reputation: 182038

Fields in format strings can be nested:

>>> print(f"{math.pi:.{n}f}")
3.14159

Upvotes: 14

Related Questions