3

Python 2.7.5+

The new style '{X.Yf}'.format(num) doesn't seem to act like the old style '%X.Yf'%(num). Can someone explain?

>>> '%8.3f' % (0.98567) ' 0.986' >>> '%8.3f' % (1.98567) ' 1.986' >>> '{num:8.3}'.format(num=0.98567) ' 0.986' >>> '{num:8.3}'.format(num=1.98567) ' 1.99' 

Note how the old style displays 3 digits after the decimal, but the new style sometimes prints 2 and sometimes 3. Am I making some silly mistake?

1 Answer 1

6

Use f in the new format too:

>>> '{num:8.3f}'.format(num=1.98567) ' 1.986' 

Without the format type, the default is g, and the precision is interpreted as the total number of digits (not counting a 0 before the decimal). With a 1 before the declimal point, only 2 digits are shown after it.

You'd see the same output with the old string formatting if you used g instead of f:

>>> '%8.3g' % (1.98567) ' 1.99' 
Sign up to request clarification or add additional context in comments.

2 Comments

The term for this is significant figures.
@JackAidley Thanks! I was sticking to terminology used in the format documentation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.