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?
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With