Rounding decimals with new Python format function

Viewed 101031

How do I round a decimal to a particular number of decimal places using the Python 3.0 format function?

5 Answers

An updated answer based on [Alex Martelli]'s solution but using Python 3.6.2 and it's updated format syntax I would suggest:

>>> n=4
>>> p=math.pi
>>> f'{p:.{n}f}'
'3.1416'

But by choosing your variables wisely your code becomes self documenting

>>> precision = 4
>>> pi = math.pi
>>> f'{pi:.{precision}f}'
'3.1416'
Related