75

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

1

5 Answers 5

127

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

Sign up to request clarification or add additional context in comments.

4 Comments

I think I read about the nesting trick before. That is quite neat, thanks for reminding me
@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!-)
Like the use of named arguments instead of {0:.{1}f}, you're right IMO it's way more readable as number:.{digits}f. Another plus is that the named arguments can be more readily recycled and don't necessarily need to be in order.
wow, I didn't know it is possible to do nested format like this
31

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'

Comments

25

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.

Comments

8

To round x to n decimal places use:

"{0:.{1}f}".format(x,n)

where 0 and 1 stand for the first and second arguments of the str.format() method, respectively.

1 Comment

Nice! With named arguments: "{x1:.4f} and {x2:.4f}".format(x1=1.23456789, x2=9.87654321) yields '1.2346 and 9.8765' (the curly braces immediately after the decimal didn't work for me, but could apparently be omitted)
5

I just found out that it is possible to combine both the {0} and the {digits} notation. This is especially useful when you want to round all variables to a pre-specified number of decimals with 1 declaration:

sName = 'Nander'
fFirstFloat = 1.12345
fSecondFloat = 2.34567
fThirdFloat = 34.5678
dNumDecimals = 2

print( '{0} found the following floats: {1:.{digits}f}, {2:.{digits}f}, {3:.{digits}f}'.format(sName, fFirstFloat, fSecondFloat, fThirdFloat, digits=dNumDecimals))
# Nander found the following floats: 1.12, 2.35, 34.57

=============================================================

EDIT:

Since all answers (including mine) where using the 'old' {0}.format() method, I'm now adding the new f-strings method (Formatted String Literals, Python 3.6+ I think) too:

x = 1.2345
y = 23.45678

print(f'x = {x:.2f} and y = {y:.2f}')
#x = 1.23 and y = 23.46

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.