String formatting with "{0:d}".format gives Unknown format code 'd' for object of type 'float'

Question:

If I understood the docs correctly, in python 2.6.5 string formatting “{0:d}” would do the same as “%d” with the String.format() way of formatting strings

" I have {0:d} dollars on me ".format(100.113)

Should print “I have 100 dollars on me “

However I get the error :

ValueError: Unknown format code ‘d’
for object of type ‘float’

The other format operations do work.for eg.

>>> "{0:e}".format(112121.2111)
'1.121212e+05'
Asked By: harijay

||

Answers:

That error is signifying that you are passing a float to the format code expecting an integer.
Use {0:f} instead. Thus:

"I have {0:f} dollars on me".format(100.113)

will give:

'I have 100.113000 dollars on me'
Answered By: Justin Waugh

Yes, you understand correctly. However you are passing float (i.e. 100.113), not int. Either convert it to int: int(100.113) or just pass 100.

Answered By: pajton

delete ‘d’, since the object type might not be a number as in my case

Answered By: Hong Ding

When using format(), or f-string (formatted strings) there are no automatic conversions from float to int. So assuming that the expected output was:

I have 100 dollars on me

The correct format spec to use would be :.0f meaning float with 0 decimal digits, which will round up/down the number for you:

"I have {0:.0f} dollars on me".format(100.113)

Some examples to show the rounding:

a = 13.1
b = 13.9
f'{a:.0f}' # 13
f'{b:.0f}' # 14
'{0:.0f}'.format(a) # 13
'{0:.0f}'.format(b) # 14
'{:.0f}'.format(a) # 13
'{:.0f}'.format(b) # 14
Answered By: RubenLaguna

ValueError: Unknown format code ‘d’ for object of type ‘float’ essentially means the interpreter is expecting an integer since you’ve provided {0:d} which is used as a placeholder to specify integer values but you’ve provided a float value instead to the format method.

And one would expect python to do this implicit type conversion from float to int since python doesn’t have a problem converting an "int to a float" or a "float value to exponential form" as you stated but this is flagged as forced type conversions by the interpreter and won’t work with format() method as of now.

So, the answer to your question is Python’s .format() method requires that the value corresponding to the d format code be of integer type.

Here are some of the alternates you could use instead:

  • "I only have {:.0f} dollars on me ".format(100.113)
  • "I only have %d dollars on me" % 100.113
Answered By: Paris
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.