Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 990
George Ogden Avatar asked Jan 28 '21 16:01

George Ogden


People also ask

How do you round to n decimal places in Python?

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.


2 Answers

Fields in format strings can be nested:

>>> print(f"{math.pi:.{n}f}")
3.14159
like image 98
Thomas Avatar answered Sep 27 '22 19:09

Thomas


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

print('{:.{}}'.format(math.pi, n)))
like image 23
BeanBagTheCat Avatar answered Sep 27 '22 20:09

BeanBagTheCat