tags:

views:

304

answers:

3

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

A: 

To round x to n decimal places use:

"{0:.nf}".format(x,y)

Where n is substituted, f tells us that the variable is treated as a float and the 0 indicates that the 0th argument of format, x, is used

Casebash
+4  A: 

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

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

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)
'3.1416'

...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!!!

Alex Martelli
I think I read about the nesting trick before. That is quite neat, thanks for reminding me
Casebash
Python is awesome!
Casebash
@Casebash, you're welcome! I do agree that the `format` approach is vastly superior to the old-fashioned, C-inspired `%`-operator based formatting -- their power's roughly equal, but `format` is _vastly_ more usable!-)
Alex Martelli
+1  A: 

In Python 3.x a format string contains replacement fields indicated by braces thus::

".... {0: format_spec} ....".format(value)

The format spec has the general layout:

[[fill]align][sign][pad][width][,][.precision][type]

So, for example leaving out all else but width, precision and type code, a decimal or floating point number could be formatted as:

>>>print("The value of pi is {0:10.7f} to 7 decimal places.".format(math.pi))

This would print as:

The value of pi is  3.1415927 to 7 decimal places.
Don O'Donnell