Python float precision without integer precision after decimal point

While working with the accuracy of the float, I came across a strange fact. Why python prints only the integer part when formatting with "%.f" . I want to know the mechanism of this

  >>> a = float(2.12345) >>> a 2.12345 >>> print "%.2f" % a 2.12 >>> print "%.1f" % a 2.1 >>> print "%f" % a 2.123450 >>> print "%.f" % a 2 #why? 

Thanks in advance for the explanation :)

+6
source share
3 answers

This has been the case since the % formatting was added back in 1993 ; if a . does not follow a decimal number, then the accuracy is taken as zero .

This is undocumented, but consistent with printf , in which the Python % formatting was inspired by:

(optional) . followed by an integer or * , or none of them indicates the precision of the conversion. In the case when * used, the precision is specified by an additional argument of type int. If the value of this argument is negative, it is ignored. If neither a number nor * is used, the precision is assumed to be zero.

Interestingly, another undocumented function, also inspired by printf , is that you can use * as precision, as mentioned above:

 >>> "%6.*f" % (2, 1.234) ' 1.23' 
+4
source

Documents for accuracy do not mention the default value here if precision is omitted. I can only assume that it works that way because it does!

The docs provide the default precision for% f as 6 in the specification mini-language format here . Perhaps specifying accuracy with. and then, omitting the integer value, the interpreter assumes that it should be zero?

It can even behave differently on different translators. Interesting to find anyway :).

Interestingly, using str.format raises a good ValueError in my interpreter 2.7:

 >>> f = 234.12345676 >>> "{:.f}".format(f) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: Format specifier missing precision 
+1
source

The % operator has the following behavior, as you noticed:

 >>> "%.f" % 1.23 '1' 

The parser passes through the format string with an accuracy of undefined ( -1 ) by default . When it reaches the value . , accuracy will be set to 0 . The arguments will be passed to the formatfloat helper function, which uses the default precision of 6 if no precision is specified, but no . is used.

It is interesting to note that str.format () will actually throw an exception in this case, perhaps to simplify the implementation and not allow people to rely on unspecified behavior:

 >>> "{:.f}".format(1.23) Traceback (most recent call last): File "<ipython-input-6-677ba2e4a680>", line 1, in <module> "{:.f}".format(1.23) ValueError: Format specifier missing precision 
+1
source

All Articles