[Tutor] float question

Alan Gauld alan.gauld at freenet.co.uk
Tue Dec 20 13:32:00 CET 2005


> what does 2 mean in %2.4f ?

In this case nothing because it will always be over-ridden by the 4.

Basically the first number specifies the *minimum* number of
characters output, ie 2 in this case.

The second number specifies the number of decimal placess
output, 4 in this case.

Since 4 decimal places plus the decimal point is 5 characters minimum,
then any value of the first digit less than 5 has no effect in this case.
To be useful at all the first digit must be greater than the second digit 
plus
one (for the decimal point). See the examples below:

>>> '%2.4f' % 456.7
'456.7000'
>>> '%2.4f' % 456.789
'456.7890'
>>> '%5.4f' % 456.789
'456.7890'
>>> '%8.4f' % 456.789
'456.7890'
>>> '%9.4f' % 456.789
' 456.7890'
>>>

Notice we always have 4 decimal digits even when we only supply 1.
And there is no difference in the overall length until the last one with
length 9, which is one greater than the length of the number expanded
to four decimals.

Does that help?

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld







More information about the Tutor mailing list