Notation "% 11f" in Python prints too many digits

In Python, I try to convert floating point numbers to strings so that the string has exactly 12 characters: the first character is a space, and the rest of the characters can be filled with the digits (and, if necessary, a decimal point) of the number to be converted to string. In addition, numbers should be expressed in decimal form (without scientific notation). I work in a fixed format in a specific file; therefore, the exact parameters indicated above. It can be assumed that all the numbers I work with are less than 1e12, i.e. All numbers can be expressed using

I use

s = " %11f" % number

Most floating point numbers are converted to a string that best suits my formatting options; however, some of the larger numbers do not. For example,

print " %11f" % 325918.166005444

gives 325918.166005. It takes 13 characters, not 11.

Why does my code do this and how can I fix it? I would like to keep as much accuracy as possible (i.e. just truncating the fractional part of a number is not a good enough solution).

If the Python version is important, I use 2.7.

+6
source share
2 answers

You did not specify precision, so the default precision is used for float 6. You need both width and precision to get the exact (not required) output.

Also note:

width - , . , .

, .

, :

>>> num = 325918.166005444
>>> w = 11
>>> " {:{w}.{p}f}".format(num, w=w, p=len(repr(num))-w-1) # subtract 1 for the dot
' 325918.1660'

, , , float , float .

+5

, , , :

num = 325918.166005444
w = 11
p = w-len(str(int(num)))-1
if p <=0: # If it short enough
   print " %11f" % num
else: # If it too long
   print " {:{w}.{p}f}".format(num, w=w, p=p)
+1

All Articles