Unknown format code 'f' for object of type 'unicode'

django, python

Solution

In your case `num` is a unicode string, which does not support the `f` format modifier:

>>> '{0:.2f}'.format(u"5.0")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'f' for object of type 'unicode'

You can fix the error making the conversion to `float` yourself:

>>> '{0:.2f}'.format(float(u"5.0"))
'5.00'

As pointed out by mgilson when you do `'{0:.2f}'.format(num)`, the `format` method of the strings calls `num.__format__(".2f")`. This results in an error for `str` or `unicode`, because they don't know how to handle this format specifier. Note that the meaning of `f` is left as an implementation for the object. For numeric types it means to convert the number to a floating point string representation, but other objects may have different conventions.

If you used the `%` formatting operator the behaviour is different, because in that case `%f` calls `__float__` directly to obtain a floating point representation of the object. Which means that when using `%`-style formatting `f` does have a specific meaning, which is to convert to a floating point string representation.

Problem

can someone tell me what is wrong with this code... ``` def format_money_value(num): return u'{0:.2f}'.format(num) ``` It gives me the following error: ``` Unknown format code 'f' for object of type 'unicode' ``` I'm running Django 1.5 Thank you

Original source