Casebash Casebash - 2 months ago 7x
Python Question

Rounding decimals with new Python format function

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



Here's a typical, useful example...:

>>> n = 4
>>> p = math.pi
>>> '{0:.{1}f}'.format(p, n)

the nested {1} takes the second argument, the current value of n, and applies it as specified (here, to the "precision" part of the format -- number of digits after the decimal point), and the outer resulting {0:.4f} then applies. Of course, you can hardcode the 4 (or whatever number of digits) if you wish, but the key point is, you don't have to!

Even better...:

>>> '{number:.{digits}f}'.format(number=p, digits=n)

...instead of the murky "argument numbers" such as 0 and 1 above, you can choose to use shiny-clear argument names, and pass the corresponding values as keyword (aka "named") arguments to format -- that can be so much more readable, as you see!!!